Java - Scanner : reading line of record separated by Pipe | as delimiter

只愿长相守 提交于 2019-12-12 12:46:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!