netbeans 如何解决无限readLine同时

mrphzbgm  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(171)

我有一个程序,我使用的方法之一是计算一个.txt文件的行数,并返回一个整数值,问题是当我执行它的时候,尽管我写了if my line is == null while必须停止,while循环继续运行,忽略它得到的空值。
我不知道该怎么解决。

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;
}

当它检测到空值时,它必须停止,这意味着没有更多的行,但它继续前进。

ddhy6vgd

ddhy6vgd1#

当你示例化一个BuffereReader并将其赋值给count时,count将总是非空的,因此将满足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.

相反,使用以下代码,其中每行都将被读取并检查是否为空,如果为空,则程序将退出。

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();
}
bogh5gae

bogh5gae2#

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;
}

相关问题