读取下一行InputStream Java

发布于 2024-11-03 07:27:13 字数 347 浏览 3 评论 0原文

我有一个可以从文本文件中读取的输入流。我注意到输入流不会从空白的下一行读取。

示例文本文件:

[This is

A test file

Here.]

代码:

while ((str = br.readLine())!= null) {
    System.out.println(str);
}

某些文本文件之间会有多个换行符。如何让输入流接受断行?

从示例文本文件中可以看出,“[This is”后跟一个空行,然后是“A test file”。如何读取两组字符串之间的空行? (这是我对换行/断线的定义)

I have an InputStream that would read from a text file. I noticed that the input stream doesn't read from a blank next line.

Sample text file:

[This is

A test file

Here.]

The code:

while ((str = br.readLine())!= null) {
    System.out.println(str);
}

Some text files would have multiple break lines in between. How do I get the input stream to accept break lines ?

As can be seen from the sample text file, '[This is' is followed by an empty line and then followed subsequently by 'A test file'. How do I read the empty line in between the two sets of strings ? (That is my definition of line break / break line)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心作怪 2024-11-10 07:27:13

你的意思是?

while ((str = br.readLine())!= null && str.trim().length()>0) {
    System.out.println(str);
}

这将为您提供所有非空行。

Do you mean?

while ((str = br.readLine())!= null && str.trim().length()>0) {
    System.out.println(str);
}

This gives you all the non blank lines.

青柠芒果 2024-11-10 07:27:13

BufferedReader 将读取文件中的所有行,无论它们是否为空。它将查找换行符:Windows 上为 LF+CR,GNU/Linux 上为 LF。根据 BufferedReader 文档:

一条线被认为是终止的
通过任何一个换行符 ('\n')、a
回车符 ('\r') 或回车符
返回,紧接着是
换行。

因此,这取决于您的文本文件的实际外观。它真的在行之间有回车符和换行符还是只是这样显示的?您可以通过在十六进制编辑器中查看该文件来找到这一点(LF 是 0x0A,CR 是 0x0D)。如果是这样,那么 BufferedReader 应该给你那些空行。

BufferedReader will read all the lines in the file regardless of whether they're blank or not. It will look for line breaks: LF+CR on Windows and LF on GNU/Linux. According to the BufferedReader documentation:

A line is considered to be terminated
by any one of a line feed ('\n'), a
carriage return ('\r'), or a carriage
return followed immediately by a
linefeed.

So, it depends on what your text file really looks like. Does it really have carriage-returns and line-feeds between the lines or is it just displaying that way? You can find this out by looking at the file in a Hex editor (LF is 0x0A and CR is 0x0D). If so, then BufferedReader should be giving you those blank lines.

哀由 2024-11-10 07:27:13

抱歉,我犯了这个错误,它是一个 BufferedReader 接收 InputStream 。 BufferedReader 确实读取了每一行,包括下一行/换行符/换行符。问题在于我编写的算法只是错过了下一行/换行符/换行符。抱歉给您带来麻烦和麻烦。

感谢所有的答案。

Sorry for the mistake, it's a BufferedReader taking in a InputStream. The BufferedReader did read every line including the next line / break line / line break. The problem was with my algorithm I wrote that simply missed the next line / break line / line break. Sorry for the hassle and trouble.

Thanks for all the answers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文