gpt4 book ai didi

java - 如何解决无限readLine while

转载 作者:行者123 更新时间:2023-12-02 01:44:00 25 4
gpt4 key购买 nike

我有一个程序,我使用的方法之一是计算 .txt 文件的行数并返回一个整数值。问题是当我执行它时,尽管我写了 if my line is == 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;
}

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

最佳答案

当您实例化 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();
}

关于java - 如何解决无限readLine while,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com