【问题标题】:Reading a text that has multiple new lines阅读包含多个换行符的文本
【发布时间】:2020-07-30 19:48:39
【问题描述】:

我有以下文字:

My name is Omer
//new line
I want to start my own personal project and achieve a lot with it
//new line
//new line
I also have problems that I encounter along the way but I know I will overcome them
//new line
Good
Bye
//new line
Bye

这就是上面的例子,我也想使用 BufferedReader。 假设我的 BufferedReader 被称为 br。 使用 br.readLine(),我可以从控制台读取行(我将输入每个字母,我也使用 InputStreamerReader)

例如,如果我这样做:

String line;
do {
line = br.readLine();
} while(line.lenght != 0)

输入新行后会停止。

如何正确阅读该文本? (我认为这是我在这里提出的第一个问题,对于我可能犯的任何错误,请见谅)

【问题讨论】:

  • while((line=br.readLine())!=null){/*...*/}

标签: java text newline bufferedreader inputstreamreader


【解决方案1】:

你可以使用:

String line;
while((line=br.readLine())!=null) {
    // your code here..
}

注意:不要使用do-while,使用while。您的输入可能从一开始就为空,并且您不希望出现 空指针异常

【讨论】:

    【解决方案2】:

    只需使用 readlines,因为 readline 只读取一行并返回

    String line;
    do {
    line = br.readLines();
    } while(line.lenght != 0)
    

    【讨论】:

      【解决方案3】:

      BufferedReader#readLine 在没有内容可读取时返回null,因此以下将起作用:

      while((line=br.readLine())!=null){
          //do something with line
      }
      

      Files.linesFiles.readAllLines 可用于简化此操作。


      如果你正在从控制台读取输入,你可以输入一个类似“exit”的字符串来表示程序应该停止读取。

      while(!(line=br.readLine()).equalsIgnoreCase("exit")){
          //do something with line
      }
      

      【讨论】:

      • 在没有内容可阅读时返回 null -> 好的,但是在输入文本后如何停止阅读?它不断要求我输入越来越多的内容:D
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 2013-08-27
      • 1970-01-01
      相关资源
      最近更新 更多