简体   繁体   中英

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. Let's say my BufferedReader is called br. Using br.readLine(), I can read lines from the console(I will input every single letter, I also use an 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 . Your input may be empty from the beginning, and you don't want to have a Null Pointer Exception .

just use readlines as readline just reads one line and return

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:

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

Files.lines or Files.readAllLines can be used to simplify this.


If you are reading input from the console, you can enter a string like "exit" to indicate that the program should stop reading.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM