【问题标题】:Use BufferedReader to recognize the end of a txt file使用 BufferedReader 识别 txt 文件的结尾
【发布时间】:2021-11-20 15:13:36
【问题描述】:

我编写的代码使用 BufferedReader 和 read() 一次一个字符地访问和读取 txt 文件中的文本。预期的结果是从 txt 文件一次打印一个单词到控制台。我目前的困难是,一旦读完整个文件,当我只想读一次时,它似乎一遍又一遍地循环遍历 txt 文件。如何防止代码重复该过程?有什么值可以让 while 循环识别吗?

https://i.stack.imgur.com/ABPQT.png

【问题讨论】:

  • 请将您的代码分享为文本,而不是图像。

标签: java while-loop bufferedreader txt


【解决方案1】:

BufferedReader.read() 返回一个int,当您到达文件末尾时,其值为-1。所以:

int read;
// Remove the reader.read() before the loop.
while ((read = reader.read()) >= 0) {
  char held = (char) read;

  // Rest of the loop.

  // Remove the reader.read() at the end of the loop.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多