[英]BufferedReader.readLine() returning all lines as null
我有一些非常简单的代码来准备txt文件的内容,逐行并将其放入String []中,但是缓冲的阅读器将所有行都返回为“null”-知道可能是什么原因吗? *我想使用缓冲阅读器而不是其他选项,因为这只是 java 培训练习的一部分,主要是我想了解我犯的错误在哪里。 谢谢!
public static void readFile (String path){
File file = new File(path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
int lineCount = (int) br.lines().count();
String[] passwords = new String[lineCount];
for (int i=0; i<lineCount; i++){
passwords[i] = br.readLine();;
System.out.println(passwords[i]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
通过使用lines()
方法,您基本上将缓冲读取器 position 移动到文件末尾。 就像您已经阅读了这些行一样。
尝试使用它来遍历所有行:
while ((line = br.readLine()) != null) {
// Use the line variable here
}
使用br.lines()
或br.readLine()
来使用输入,但不能同时使用两者。 此版本仅使用 stream 到 String[] 执行相同的操作,并在 try with resources 块中关闭输入:
public static String[] readFile(Path path) throws IOException {
try (BufferedReader br = Files.newBufferedReader(path);
Stream<String> stream = br.lines()) {
return stream.peek(System.out::println)
.collect(Collectors.toList())
.toArray(String[]::new);
}
}
String[] values = readFile(Path.of("somefile.txt"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.