问题
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
来源:https://stackoverflow.com/questions/9177039/java-scanner-reading-line-of-record-separated-by-pipe-as-delimiter