L
Lee Weiner
I teach Java, and we're switching to 1.5.0 next semester. I was thinking
about using the Scanner class to read data from text files, but I'm having
a problem specifying a delimiter string.
The file I'm using for the following example contains two records:
Weiner@572-6544@57
Kirby@572-6544@36
Using the following:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
public class ScannerFile
{
public static void main ( String[] args )
{
try
{
Scanner scan = new Scanner( new File( "lee.txt" ) );
scan.useDelimiter( "\\s+" ); //1 or more white space chars
while( scan.hasNext() )
{
System.out.println( "*" + scan.next() + "*" );
}
scan.close();
}
catch(FileNotFoundException exc)
{
System.out.println( "Error - Input file not found. Terminating." );
System.exit( 1 );
}
System.exit(0);
}
}
I get:
*Weiner@572-6544@57*
*Kirby@572-6544@36*
Exactly what I expect, but if I also want to delimit on the "@" signs with
scan.useDelimiter( "[@\\s+]" );
I get:
*Weiner*
*572-6544*
*57*
**
*Kirby*
*572-6544*
*36*
**
Can anyone tell me what I'm doing to cause that extra empty token at the
end of each record? I running under WindowsXP, if that's important.
Lee Weiner
lee AT leeweiner DOT org
about using the Scanner class to read data from text files, but I'm having
a problem specifying a delimiter string.
The file I'm using for the following example contains two records:
Weiner@572-6544@57
Kirby@572-6544@36
Using the following:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
public class ScannerFile
{
public static void main ( String[] args )
{
try
{
Scanner scan = new Scanner( new File( "lee.txt" ) );
scan.useDelimiter( "\\s+" ); //1 or more white space chars
while( scan.hasNext() )
{
System.out.println( "*" + scan.next() + "*" );
}
scan.close();
}
catch(FileNotFoundException exc)
{
System.out.println( "Error - Input file not found. Terminating." );
System.exit( 1 );
}
System.exit(0);
}
}
I get:
*Weiner@572-6544@57*
*Kirby@572-6544@36*
Exactly what I expect, but if I also want to delimit on the "@" signs with
scan.useDelimiter( "[@\\s+]" );
I get:
*Weiner*
*572-6544*
*57*
**
*Kirby*
*572-6544*
*36*
**
Can anyone tell me what I'm doing to cause that extra empty token at the
end of each record? I running under WindowsXP, if that's important.
Lee Weiner
lee AT leeweiner DOT org