Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner class skips over whitespace

Tags:

java

arrays

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.

like image 602
Casper Avatar asked Aug 10 '13 05:08

Casper


3 Answers

This will work for you

Scanner scanner = new Scanner(new File("D:\\sample.txt"));
    while (scanner.hasNextLine()) {
        String token = scanner.nextLine();
        System.out.println(token);

    }
like image 165
Ruchira Gayan Ranaweera Avatar answered Oct 15 '22 14:10

Ruchira Gayan Ranaweera


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.

like image 15
Hovercraft Full Of Eels Avatar answered Nov 10 '22 16:11

Hovercraft Full Of Eels


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

like image 4
Ankur Lathi Avatar answered Nov 10 '22 16:11

Ankur Lathi