Scanner class skips over whitespace

I am using a nested Scanner loop to extract the digit from a string line (from a text file) as follows:

String str = testString;            
Scanner scanner = new Scanner(str); 
while (scanner.hasNext()) {
    String token = scanner.next();
    // Here each token will be used
}

The problem is this code will skip all the spaces " ", but I also need to use those "spaces" too. So can Scanner return the spaces or I need to use something else?

My text file could contain something like this:

0
011
abc
d2d

sdwq

sda

Those blank lines contains 1 " " each, and those " " are what I need returned.


Solution 1:

Use Scanner's hasNextLine() and nextLine() methods and you'll find your solution since this will allow you to capture empty or white-space lines.

Solution 2:

By default, a scanner uses white space to separate tokens.

Use Scanner#nextLine method, Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

To use a different token separator, invoke useDelimiter(), specifying a regular expression. For example, suppose you wanted the token separator to be a comma, optionally followed by white space. You would invoke,

scanner.useDelimiter(",\\s*");

Read more from http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Solution 3:

You have to understand what is a token. Read the documentation of Scanner:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

You could use the nextLine() method to get the whole line and not "ignore" with any whitespace.

Better you could define what is a token by using the useDelimiter method.