Danne132
Danne132

Reputation: 3

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.

Upvotes: 0

Views: 5087

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1075427

I think I may be misunderstanding. Assuming you have a BufferedReader, your main processing loop would be:

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:

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. 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).

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 692121

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(""))

Upvotes: 2

Kevin Bowersox
Kevin Bowersox

Reputation: 94489

Try checking the length of the line:

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

Upvotes: 1

Related Questions