[英]How do I use BufferedReader to read lines from a txt file into an array
我知道如何阅读Scanner
,但我如何使用BufferedReader
? 我希望能够将行读入数组。 我能够将hasNext()
函数与Scanner
但不是BufferedReader
,这是我唯一不知道该怎么做的事情。 如何检查何时到达文件结尾?
BufferedReader reader = new BufferedReader(new FileReader("weblog.txt"));
String[] fileRead = new String[2990];
int count = 0;
while (fileRead[count] != null) {
fileRead[count] = reader.readLine();
count++;
}
该文档指出 ,如果到达流的末尾, readLine()
将返回null
。
通常的习惯用法是更新在while条件中保存当前行的变量,并检查它是否不为null:
String currentLine;
while((currentLine = reader.readLine()) != null) {
//do something with line
}
另外,您可能事先不知道要读取的行数,因此我建议您使用列表而不是数组。
如果您打算阅读所有文件的内容,则可以使用Files.readAllLines
:
//or whatever the file is encoded with
List<String> list = Files.readAllLines(Paths.get("weblog.txt"), StandardCharsets.UTF_8);
readLine()
在到达EOF
后返回null
。
只是
do {
fileRead[count] = reader.readLine();
count++;
} while (fileRead[count-1]) != null);
当然这段代码不是推荐的读取文件的方法,但是如果你想要按照你想要的方式(一些预定义的大小数组,计数器等)完成它,它会显示如何完成它。
使用readLine()
, try-with-resources
和Vector
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\weblog.txt")))
{
String line;
Vector<String> fileRead = new Vector<String>();
while ((line = bufferedReader.readLine()) != null) {
fileRead.add(line);
}
} catch (IOException exception) {
exception.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.