Java - Scanner : reading line of record separated

2019-07-07 08:41发布

问题:

I want to read a text file where fields data are separated by delimiter | (pipe symbol).

But some unexpected happened :

Here is my code :

doScannerTest ("Y~2011~GT~Nepal~Ganesh~Tiwari~N", "~");
doScannerTest("Y|2011|GT|Nepal|Ganesh|Tiwari|N", "|");

private static void doScannerTest(String recordLine, String delim) {
    java.util.Scanner lineScanner = new java.util.Scanner(recordLine);
    lineScanner.useDelimiter(delim);
    while (lineScanner.hasNext()) {
        System.out.println(lineScanner.next());
    }
}

The delim ~ works fine but | prints all characters in recordLine.

Why the record with delim | is not working ? I cannot change the framework code(which uses Scanner) and use String Split.

回答1:

the pipe character is a reserved regex character, you will need to escape it. for example you need to use

\\|

putting that in your code gives the below output

  • Y
  • 2011
  • GT
  • Nepal
  • Ganesh
  • Tiwari
  • N