如何解决无限的readLine而

时间:2018-12-30 16:32:10

标签: java file netbeans

我有一个程序,我使用的一种方法是计算.txt文件的行数并返回一个整数值。问题是当我执行它时,尽管我写了如果我的行是== null,则while必须停止,而while继续前进,而忽略了他无限得到的null。

我不知道该怎么解决。

private int sizeOfFile (File txt) {
    FileReader input = null;
    BufferedReader count = null;
    int result = 0;
    try {

        input = new FileReader(txt);
        count = new BufferedReader(input);

        while(count != null){
        String line = count.readLine();
            System.out.println(line);
        result++;
        }

    } catch (FileNotFoundException ex) {
       ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            input.close();
            count.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    return result;
}

当他检测到空值时必须停止,这意味着不再有任何行,但它仍在继续。

2 个答案:

答案 0 :(得分:2)

实例化一个BuffereReader并将其分配给count时,count将始终为非null,因此将满足while循环:

count = new BufferedReader(input); //count is holding an instance of BufferedReader.

while(count != null){ //here count is non-null and while loop is infinite and program never exits.

请改为使用以下代码,其中将读取每一行并检查其是否为null,如果为null,则程序将退出。

input = new FileReader(txt);
count = new BufferedReader(input);
String line = null;
while(( line = count.readLine())!= null){ //each line is read and assigned to the String line variable.
        System.out.println(line);
        result++;
 }

如果您使用的是JDK-1.8,则可以使用Files API缩短代码:

int result = 0;
try (Stream<String> stream = Files.lines(Paths.get(txt.getAbsolutePath()))) {
      //either print the lines or take the count.
      //stream.forEach(System.out::println); 
      result = (int)stream.count(); 
} catch (IOException e) {
      e.printStackTrace();
}

答案 1 :(得分:0)

count是您的BufferedReader,您的循环应该在line上!喜欢,

String line = "";
while (line != null) {
    line = count.readLine();

此外,您应该使用try-with-Resourcesclose(而不是finally块)来使用资源。而且您可以更习惯地写while循环。喜欢,

private int sizeOfFile(File txt) {
    int result = 0;
    try (BufferedReader count = new BufferedReader(new FileReader(txt))) {
        String line;
        while ((line = count.readLine()) != null) {
            System.out.println(line);
            result++;
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return result;
}