读取具有多个换行符的文本

huangapple go评论134阅读模式
英文:

Reading a text that has multiple new lines

问题

以下是您要翻译的内容:

我有以下文本:

我的名字是Omer
//新行
我想开始我的个人项目并取得很大的成就
//新行
//新行
在我前进的过程中我也会遇到问题,但我知道我会克服它们
//新行
好的
再见
//新行
再见

那就是上面的示例,我还想使用一个BufferedReader。
假设我的BufferedReader叫做br。
使用br.readLine(),我可以从控制台读取行(我将输入每个字母,我还使用InputStreamerReader)

如果我做如下操作:

String line;
do {
line = br.readLine();
} while(line.lenght != 0)

它会在我输入一个新行后停止。

如何正确读取这段文本?(我认为这是我在这里的第一个问题,对于我可能犯的任何错误,对此表示抱歉)

英文:

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)

答案1

得分: 1

你可以使用:

String line;
while((line=br.readLine())!=null) {
    // 在这里编写你的代码..
}

注意: 不要使用 do-while,使用 while。你的输入可能从一开始就是空的,你不希望出现 Null Pointer Exception

英文:

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.

答案2

得分: 0

只使用readlines而不是readline,因为readline只读取一行并返回。

String line;
do {
    line = br.readLines();
} while(line.length() != 0)
英文:

just use readlines as readline just reads one line and return

String line;
do {
line = br.readLines();
} while(line.lenght != 0)

答案3

得分: 0

BufferedReader#readLine 在没有可读内容时返回 null,因此以下代码将有效:

while ((line = br.readLine()) != null) {
    // 对 line 做一些处理
}

Files.linesFiles.readAllLines 可以用于简化此操作。

如果你正在从控制台读取输入,你可以输入字符串 "exit" 表示程序应该停止读取。

while (!(line = br.readLine()).equalsIgnoreCase("exit")) {
    // 对 line 做一些处理
}
英文:

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.

<hr/>

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(&quot;exit&quot;)){
    //do something with line
}

huangapple
  • 本文由 发表于 2020年7月31日 03:48:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63180358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定