Skip to content
Advertisement

How to deal with whitespaces when reading a file with a scanner

I am writing a program where I read data from a file name that the user inputs using a scanner. I am making a new object from each line of the file using the following code:

 while (scan.hasNextLine()) {
        String line = scan.nextLine();
        String[] parts = line.split(" ");
        //create new object from parts here 
}

This works correctly until my file for .txt files where there is no whitespace in between the lines but when there is a blank line in between words it stops working entirely.

Right now it only works on a .txt file set up like this:

line 1
line 2
line 3

I want to set it up to read a file like this:

line 1

line 2

line 3

How can I modify my program to read over a blank line and check if there is text after it?

Advertisement

Answer

You can test the first value in your parts array, which will always exist.

while (scan.hasNextLine()) {
    String line = scan.nextLine();
    String[] parts = line.split(" ");
    if (!parts[0].isEmpty()) {
        //create new object from parts here 
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement