[英]Reading a text that has multiple new lines
I have the following text:我有以下文字:
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
So that was the example above, I also want to use a BufferedReader.这就是上面的例子,我也想使用 BufferedReader。 Let's say my BufferedReader is called br.
假设我的 BufferedReader 被称为 br。 Using br.readLine(), I can read lines from the console(I will input every single letter, I also use an InputStreamerReader)
使用 br.readLine(),我可以从控制台读取行(我将输入每个字母,我也使用 InputStreamerReader)
If I do for example:例如,如果我这样做:
String line;
do {
line = br.readLine();
} while(line.lenght != 0)
It will stop after I enter a new line.输入新行后它将停止。
How can I read that text correctly?我怎样才能正确阅读该文本? (I think that this is the first question that I ask here, sorry for any mistakes that I have maybe made)
(我认为这是我在这里提出的第一个问题,对于我可能犯的任何错误,我深表歉意)
You can use:您可以使用:
String line;
while((line=br.readLine())!=null) {
// your code here..
}
Note: don't do do-while
, use while
.注意:不要做
do-while
,使用while
。 Your input may be empty from the beginning, and you don't want to have a Null Pointer Exception .您的输入可能从一开始就为空,并且您不希望有Null Pointer Exception 。
just use readlines as readline just reads one line and return只需使用 readlines 作为 readline 只读取一行并返回
String line;
do {
line = br.readLines();
} while(line.lenght != 0)
BufferedReader#readLine
returns null
when there is nothing left to read, so the following will work: BufferedReader#readLine
在没有内容可读取时返回null
,因此以下操作将起作用:
while((line=br.readLine())!=null){
//do something with line
}
Files.lines
or Files.readAllLines
can be used to simplify this. Files.lines
或Files.readAllLines
可用于简化此操作。
If you are reading input from the console, you can enter a string like "exit" to indicate that the program should stop reading.如果您正在从控制台读取输入,您可以输入类似“exit”的字符串来指示程序应该停止读取。
while(!(line=br.readLine()).equalsIgnoreCase("exit")){
//do something with line
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.