简体   繁体   English

从 Java 中的文本文件中读取行

[英]Reading lines from text files in Java

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.提前感谢您的帮助。

I think I may be misunderstanding.我想我可能是误会了。 Assuming you have a BufferedReader , your main processing loop would be:假设您有一个BufferedReader ,您的主要处理循环将是:

br = /* ...get the `BufferedReader`... */;
while ((line = br.readLine()) != null) {
    line = line.trim();
    if (line.length() == 0) {
        continue;
    }

    // Process the non-blank lines from the input here
}

Update : Re your comment:更新:回复您的评论:

For example if I want to read the line after name, if that line is blank or empty, I want to read the line after that.例如,如果我想读取名称之后的行,如果该行是空白或空的,我想读取之后的行。

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:以上是我将如何构建我的处理循环,但如果您愿意,您可以简单地使用返回下一个非空行的 function:

String readNonBlankLine(BufferedReader br) {
    String line;

    while ((line = br.readLine()) != null) {
        if (line.trim().length() == 0) {
            break;
        }
    }
    return line;
}

That returns null at EOF like readLine does, or returns the next line that doesn't consist entirely of whitespace.这会像readLine一样在 EOF 处返回null ,或者返回不完全由空格组成的下一行。 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:要测试它是否为空,只需将其与空字符串进行比较:

if (line.equals(""))

This won't work with lines with spacing characters (space, tabs), though.但是,这不适用于带有空格字符(空格、制表符)的行。 So you might want to do所以你可能想做

if (line.trim().equals(""))

Try checking the length of the line:尝试检查行的长度:

 String line;
 while((line= bufreader.readLine()) != null)
    if (line.trim().length() != 0)
       return line;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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