这是我以前写的一个,看看怎么样 import java.io.*;public class GetFileLines { public static void main(String[] args) throws IOException { int countLine = 0; // record the line of the file BufferedReader in; String s = new String(); // get the value of readLine(); try { in = new BufferedReader(new FileReader(args[0])); } catch (FileNotFoundException e) { e.printStackTrace(); return ; } while((s = in.readLine()) != null) countLine++; System.out.println("The lines of files is " + countLine); } }
这个也不行 只有读完文件才行
setlineNumber
这样做可能省一半的时间,但是由于使用线程而增加了出错的可能性,似乎有点得不偿失;)
我想,先用获取整个文件的长度,再一次性读到一个char[]中,再进行判断.由于减少了读文件的次数,是不是能减少读文件的时间呢?
使用char[]和BufferedString究竟谁快我没有测试过
String的实现是用char[]
估计BufferedString的实现也是用char[]的
刚把源码删了,不能查了,不过我记得是
File test= new File("test.txt");
long fileLength = test.length();
LineNumberReader rf = null;
try {
rf = new LineNumberReader(new FileReader(test));
if (rf != null) {
int lines = 0;
rf.skip(fileLength);
lines = rf.getLineNumber();
rf.close();
}
} catch (IOException e) {
if (rf != null) {
try {
rf.close();
} catch (IOException ee) {
}
}
}
import java.io.*;public class GetFileLines { public static void main(String[] args) throws IOException
{
int countLine = 0; // record the line of the file
BufferedReader in;
String s = new String(); // get the value of readLine();
try {
in = new BufferedReader(new FileReader(args[0]));
} catch (FileNotFoundException e) {
e.printStackTrace();
return ;
}
while((s = in.readLine()) != null)
countLine++; System.out.println("The lines of files is " + countLine); }
}