0

I am trying to figure out how to read in a series of values from a file in java. The file has multiple lines and the values are separated with commas in each line. While writing a test program just to figure out how to use a delimiter with Scanner I ran into an issue with my program printing values from the file. I don't know where the program is getting instructions to print all the values from.

This is what is in my public static void main (inside a try loop):

File f1 = new File("Data1.txt");
File test = new File("test.txt");
Scanner reader = new Scanner(f1);
Scanner testReader = new Scanner(test);
testReader.useDelimiter(",");

System.out.println("line 18 "+testReader.nextInt());
System.out.println("line 19 "+testReader.nextInt());
System.out.println("line 20 "+testReader.next());
System.out.println("line 21 "+testReader.nextInt());

The file I am reading from is test.txt:

4,5,6 
7 
8,9,10

And this is what is being printed:

line 18 4
line 19 5
line 20 6
7
8
line 21 9
Ganlas
  • 51
  • 7

2 Answers2

1

You need to add the new-line characters as well to the delimiter pattern:

testReader.useDelimiter(",|(\r\n)|(\n)");
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • Thank you! One more thing, I presume \n represents a newline character, but what does \r represent? – Ganlas Mar 05 '20 at 18:07
  • Windows uses `\r\n` to represent new-line, while Linux/MacOS use `\n`. – Eng.Fouad Mar 05 '20 at 18:08
  • @Ganlas [\r\n, \r and \n what is the difference between them?](https://stackoverflow.com/questions/15433188/r-n-r-and-n-what-is-the-difference-between-them) – MT756 Mar 05 '20 at 18:52
1

Your scanner is not seeing the linefeed characters as delimiters. This is the reason why the linefeed characters get returned by scanner.next()

Solution is to configure the scanner to have space and comma as delimiters:

testReader.useDelimiter("(,|\\s)");

See here for more info on patterns like "(,|\\s)".

s.fuhrm
  • 438
  • 4
  • 9