Java 对文件的操作
public class ReadFile { /** * 按行读取文件操作 * @throws IOException */ public void readFile(String fileName) throws IOException{ //(1)File 类 File file = new File(fileName); // BufferedReader reader = null; try { //(2) 将文件放入到BufferedReader中 reader = new BufferedReader(new FileReader(file)); String temp = null; int line = 0; while( (temp = reader.readLine()) != null){ System.out.println(temp + (++line)); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ reader.close(); } } /** * 文件的写入操作 */ public void writeFile(String fileName, String str) throws IOException{ File file = new File(fileName); //true实现对文件的追加操作 FileWriter ws = new FileWriter(file,true); ws.write(str); ws.close(); } /** * 对于一个大文本文件,我们仅仅读取最后的N行 * @throws IOException */ public String[] getLastNFromFile(String fileName) throws IOException{ String []temp = new String[5]; File f = new File(fileName); BufferedReader reader = new BufferedReader(new FileReader(f)); String temp1 = null; int line = 0; while((temp1 = reader.readLine()) != null){ temp[line++]= temp1; if(line >= 5 ){ line = 0; } } return temp; } /** * 通过索引进行操作 * @throws IOException */ public String[] getLastNFromFileByIndex(String fileName) throws IOException{ String []temp = new String[5]; File f = new File(fileName); BufferedReader reader = new BufferedReader(new FileReader(f)); String temp1 = null; int line = 0; while((temp1 = reader.readLine()) != null){ line++; } return temp; } }
对2000000行的文件进行操作,读取最后的5行,并没有发现直接通过行索引和通过一个数组进行栈式进入有什么差别!
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。