[英]Reading a text that has multiple new lines
我有以下文字:
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)
输入新行后它将停止。
我怎样才能正确阅读该文本? (我认为这是我在这里提出的第一个问题,对于我可能犯的任何错误,我深表歉意)
您可以使用:
String line;
while((line=br.readLine())!=null) {
// your code here..
}
注意:不要做do-while
,使用while
。 您的输入可能从一开始就为空,并且您不希望有Null Pointer Exception 。
只需使用 readlines 作为 readline 只读取一行并返回
String line;
do {
line = br.readLines();
} while(line.lenght != 0)
BufferedReader#readLine
在没有内容可读取时返回null
,因此以下操作将起作用:
while((line=br.readLine())!=null){
//do something with line
}
Files.lines
或Files.readAllLines
可用于简化此操作。
如果您正在从控制台读取输入,您可以输入类似“exit”的字符串来指示程序应该停止读取。
while(!(line=br.readLine()).equalsIgnoreCase("exit")){
//do something with line
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.