在Java中,如何使用此countLines方法计算没有换行符的行?

时间:2015-11-20 15:26:55

标签: java

以下代码对文本文件中的行进行计数,但如果有一行没有换行符('\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:错误:无法比较的类型:字节和&#39;&#39;

    if (c[i] == '\n'    || c[i] != null  ) {

2 个答案:

答案 0 :(得分:4)

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();

答案 1 :(得分:2)

您没有正确使用empty标记。不要在嵌套循环之前将其初始化为false,而是在字符为true时将其设置为'\n',而在不是false时将其设置为boolean empty = true; while ((readChars = is.read(c)) != -1) { for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++count; empty = true; } else { empty = false; } } } if (!empty) { count++; } return count;

empty

到达方法的末尾后,使用<html> <head> <style> body { counter-reset: chapter 3 section 0; } h2 { counter-reset: slide 0; counter-increment: section; } h3 { counter-increment: slide; } h1:before { content: counter(chapter) ". "; } h2:before { content: counter(chapter) "." counter(section) " "; } h3:before { content: counter(chapter) "." counter(section) "." counter(slide) " "; } </style> </head> <body> <article> <h1>chapter</h1> </article> <article> <h2>section A</h2> </article> <article> <h3> slide a</h3> </article> <article> <h3> slide b</h3> </article> <article> <h2>section B</h2> </article> <article> <h3> slide a</h3> </article> <article> <h3> slide b</h3> </article> </body> </html> 来决定是否应增加行数。这将涵盖文件包含多行的情况。