[英]How do I use BufferedReader to read lines from a txt file into an array
I know how to read in lines with Scanner
, but how do I use a BufferedReader
? 我知道如何阅读
Scanner
,但我如何使用BufferedReader
? I want to be able to read lines into an array. 我希望能够将行读入数组。 I am able to use the
hasNext()
function with a Scanner
but not a BufferedReader
, that is the only thing I don't know how to do. 我能够将
hasNext()
函数与Scanner
但不是BufferedReader
,这是我唯一不知道该怎么做的事情。 How do I check when the end of the file text has been reached? 如何检查何时到达文件结尾?
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++;
}
The documentation states that readLine()
returns null
if the end of the stream is reached. 该文档指出 ,如果到达流的末尾,
readLine()
将返回null
。
The usual idiom is to update the variable that holds the current line in the while condition and check if it's not null: 通常的习惯用法是更新在while条件中保存当前行的变量,并检查它是否不为null:
String currentLine;
while((currentLine = reader.readLine()) != null) {
//do something with line
}
As an aside, you might not know in advance the number of lines you will read, so I suggest you use a list instead of an array. 另外,您可能事先不知道要读取的行数,因此我建议您使用列表而不是数组。
If you plan to read all the file's content, you can use Files.readAllLines
instead: 如果您打算阅读所有文件的内容,则可以使用
Files.readAllLines
:
//or whatever the file is encoded with
List<String> list = Files.readAllLines(Paths.get("weblog.txt"), StandardCharsets.UTF_8);
readLine()
returns null
after reaching EOF
. readLine()
在到达EOF
后返回null
。
Just 只是
do {
fileRead[count] = reader.readLine();
count++;
} while (fileRead[count-1]) != null);
Of course this piece of code is not the recommended way of reading the file, but shows how it might be done if you want to do it exactly the way you attempted to ( some predefined size array, counter etc. ) 当然这段代码不是推荐的读取文件的方法,但是如果你想要按照你想要的方式(一些预定义的大小数组,计数器等)完成它,它会显示如何完成它。
using readLine()
, try-with-resources
and Vector
使用
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.