Java读取文件的行数大体来说有两种方法,一种就是一行一行的读取,然后做count,代码如下:
public int count(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n')
++count;
}
}
return count;
} finally {
is.close();
}
}
另一种就是使用LineNumberReader类,但是使用这个类要得到全文的行数也得做个循环
public int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
int cnt = 0;
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {}
cnt = reader.getLineNumber();
reader.close();
return cnt;
}
本文介绍了两种使用Java读取文件并统计行数的方法。第一种方法通过逐字符读取文件并计数换行符来确定行数;第二种方法利用LineNumberReader类遍历文件并获取当前行数。
433

被折叠的 条评论
为什么被折叠?



