首页 > 解决方案 > 阅读包含多个换行符的文本

问题描述

我有以下文字:

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)

输入新行后它将停止。

我怎样才能正确阅读该文本?(我认为这是我在这里提出的第一个问题,对于我可能犯的任何错误,我深表歉意)

标签: javatextnewlinebufferedreaderinputstreamreader

解决方案


您可以使用:

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

注意:不要这样做do-while,使用while. 您的输入可能从一开始就为空,并且您不希望出现Null Pointer Exception


推荐阅读