以下代码计算文本文件中的行数,但如果有一行没有换行符 ('\n'
),则不会计算它们:
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n' /* || c[i] != null */ ) {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
当我尝试将代码 c[i] != null
添加到 if 条件中时,它给出了这个错误:
NewParentClass.java:72: error: incomparable types: byte and ''
if (c[i] == '\n' || c[i] != null ) {
最佳答案
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();
关于java - 在 Java 中,我如何使用这个 countLines 方法来计算没有换行符的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33830298/