【问题标题】:How do I use BufferedReader to read lines from a txt file into an array如何使用 BufferedReader 将 txt 文件中的行读入数组
【发布时间】:2015-07-28 21:55:16
【问题描述】:

我知道如何使用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++;
}

【问题讨论】:

标签: java file bufferedreader


【解决方案1】:

readLine() 返回null 到达EOF

只是

do {
  fileRead[count] = reader.readLine();
  count++;
} while (fileRead[count-1]) != null);

当然,这段代码不是读取文件的推荐方式,但它显示了如果您想完全按照您尝试的方式(一些预定义大小的数组、计数器等)来完成它。

【讨论】:

  • 正确的方法是使用某种列表对吗?我刚刚进入 i/o 并没有任何具体的方法来学习文本/二进制 io 上的 rite 方法。对于这个例子,我只是想看看这种特殊的存储方式是可能的。谢谢!
  • @HugoPerea 是的,列表非常灵活,非常适合存储未知数量的对象。它们还可以减少对计数器的需求,因为您可以使用其 size() 方法检查列表中的对象数量。
  • @HugoPerea “正确的方法是使用某种列表对吗?” 为了避免将不属于读取文本文件的内容添加到您的收藏中,就像这段代码目前所做的那样。
  • 阅读大文本文件的最佳组合是什么?我的老师使用扫描仪和 FileInputStream。
【解决方案2】:

如果到达流的末尾,readLine() 返回 nulldocumentation states

通常的习惯用法是在while条件下更新保存当前行的变量,并检查它是否不为空:

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

【讨论】:

    【解决方案3】:

    使用readLine()try-with-resourcesVector

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      相关资源
      最近更新 更多