簡體   English   中英

閱讀包含多個換行符的文本

[英]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.linesFiles.readAllLines可用於簡化此操作。


如果您正在從控制台讀取輸入,您可以輸入類似“exit”的字符串來指示程序應該停止讀取。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM