Using a Scanner to Extract Line-Delimited Data
I am fetching data from a file. I am having problems using delimiters when reading a file.
My file is ordered like this:
0 Name 0
1 Name1 1
The structure is an integer, tab (\ t), string, tab (\ t), another integer, and then a newline (\ n).
I tried using a compound delimiter as stated in this question: Java - using multiple delimiters in a scanner
However, I still get an InputMismatch exception when I run the following code:
while(readStations.hasNextLine()) {
327 tempSID = readStations.nextInt();
328 tempName = readStations.next();
329 tempLine = readStations.nextInt();
//More code here
}
It throws this error on line 2 of the above code ... I'm not sure why and help would be appreciated, thanks.
The current output is executed as such for the code:
Exception in thread "main" java.util.InputMismatchException
...stuff...
at Metro.declarations(Metro.java:329)
+3
source to share
2 answers
The newline is most likely causing you problems. try it
public class TestScanner {
public static void main(String[] args) throws IOException {
try {
Scanner scanner = new Scanner(new File("data.txt"));
scanner.useDelimiter(System.getProperty("line.separator"));
while (scanner.hasNext()) {
String[] tokens = scanner.next().split("\t");
for(String token : tokens) {
System.out.print("[" + token + "]");
}
System.out.print("\n");
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
+1
source to share