user40380
user40380

Reputation: 76

Empty line in file

I could not find an explanation and those I found I am unsure of. So please confirm my doubts:

I am reading through a file using a while loop and if the line in the file is empty it skips and goes to next line. I just want to make sure the code I am using is correct for the what I just described:

while((strLine = reader.readLine())!= null)  <----- While loop that is suppose to read Line by Line
{           
    if (strLine.isEmpty() == false) <----- Check for empty Line
    {
        /** My Code **/
    } 
    else 
    {
    /** My Code **/
    }
}   

Upvotes: 0

Views: 112

Answers (4)

natsirun
natsirun

Reputation: 28

Yes! What you are doing is what you want to do. You can just try compiling it yourself, you know. Trial and error. If you could not figure out how to use the reader, as the other answers propose, here you go:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Trial {

    public static void main(String[] args) throws IOException {
        String strLine;
        BufferedReader reader = new BufferedReader(new FileReader(
                "/home/user234/folder1/filename"));
        while ((strLine = reader.readLine()) != null) {
            if (!strLine.isEmpty()) {
                System.out.println("notEMPTY");
            } else {
                System.out.println("EMPTY");
            }
        }
    }
}

Upvotes: 1

bcorso
bcorso

Reputation: 47176

The Java Reader does not have a readline() method.

If you want to do specific parsing of tokens you should use the Scanner. Scanner has a nextLine() method to grab each line, but throws an Exception if there is no next line. Therefore you should use Scanner.hasNextLine() for your while condition.

Scanner s = new Scanner("filename.txt");
String line;

while(s.hasNextLine()){                            // check for next line
    line = s.nextLine();                           // get next line
    if(line == ""){                                // check if line is empty
        System.out.println("Empty");
    } else {
        System.out.println("Not Empty:" + line);
    }
}   

Here's a live Example using Ideone.


EDIT: The BufferedReader does have a readline() method, as used by @natsirun. Although for any file parsing more complicated than line reading you would prefer the Scanner.

Upvotes: 0

mikey13579
mikey13579

Reputation: 11

The logic shown in the above code makes sense to what you have described. It should perform what you desire.

Upvotes: 0

Dumindu Madushanka
Dumindu Madushanka

Reputation: 504

yes. it will work fine.

while(/* While scanner has next line */)
{
   line = scanner.nextLine();
   if( /* line is not equal to null */) {

    /* perform code */

    }
}

Upvotes: 1

Related Questions