用 Java 从文本文件中读取行
我正在尝试从一些文本文件中读取产品信息。在我的文本文件中,我有产品及其信息。
这是我的文件:
Product1: ID: 1232 Name: ABC35 InStock: Yes
如您所见,有些产品的产品信息中有空行,我想知道是否有什么好的方法来确定该行是否为空,然后读取下一行。
我怎样才能做到这一点?如果读取行为空白,则读取下一行。
预先感谢您的任何帮助。
I am trying to read product information from some text files. In my text file I have products and their information.
This is my file:
Product1: ID: 1232 Name: ABC35 InStock: Yes
As you see, some products have blank lines in their product information, and I was wondering if there is any good way to determine if the line is blank, then read the next line.
How can I accomplish that? If the reading line is blank, then read the next line.
Thanks in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想我可能有误解。假设您有一个 BufferedReader,您的主要处理循环将是:
更新:回复您的评论:
上面是我构建处理循环的方式,但如果您愿意,您可以简单地使用返回下一个非空行的函数:
它在 EOF 处返回
null
,如readLine
code> 执行此操作,或者返回不完全由空格组成的下一行。请注意,它不会从行中删除空格(我上面的处理循环会这样做,因为通常当我这样做时,我希望将空格修剪掉,即使它们不是空白)。I think I may be misunderstanding. Assuming you have a
BufferedReader
, your main processing loop would be:Update: Re your comment:
The above is how I would structure my processing loop, but if you prefer, you can simply use a function that returns the next non-blank line:
That returns
null
at EOF likereadLine
does, or returns the next line that doesn't consist entirely of whitespace. Note that it doesn't strip whitespace from the line (my processing loop above does, because usually when I'm doing this, I want the whitespace trimmed off lines even if they're not blank).只需循环文件中的所有行,如果其中一行为空,则忽略它。
要测试它是否为空,只需将其与空字符串进行比较即可:
但这不适用于带有空格字符(空格、制表符)的行。所以你可能想做
Simply loop over all the lines in the file, and if one is blank, ignore it.
To test if it's blank, just compare it to the empty String:
This won't work with lines with spacing characters (space, tabs), though. So you might want to do
尝试检查线的长度:
Try checking the length of the line: