如何使扫描仪正确读取转义字符?

san*_*ngh 7 java java.util.scanner

我正在阅读一个文件,该文件在一行中读取所有内容:

Hello World!\nI've been trying to get this to work for a while now.\nFrustrating.\n
Run Code Online (Sandbox Code Playgroud)

我的扫描仪从文件中读取并将其放入字符串中:

Scanner input = new Scanner(new File(fileName));
String str = input.nextLine();
System.out.print(str);
Run Code Online (Sandbox Code Playgroud)

现在,我希望输出为:

Hello World!
I've been trying to get this work for a while now.
Frustrating.
Run Code Online (Sandbox Code Playgroud)

但相反,我得到了与输入完全相同的东西.也就是说,每个\n都包含在输出中,并且所有内容都在一行而不是单独的行.

我认为Scanner能够正确地读取转义字符,但它反而将它复制到字符串上,就像它的\n一样.

ala*_*inm 4

如果\n写入的是您无法使用的文件nextLine(),因为没有\n(行尾)而是有\\n(两个字符)。

相反,尝试使用分隔符:

    Scanner sc = new Scanner(new File("/home/alain/Bureau/ttt.txt"));
    sc.useDelimiter("\\\\n");
    while(sc.hasNext()){
        System.out.println(sc.next());
    }
Run Code Online (Sandbox Code Playgroud)

输出 :

你好世界!

我已经尝试让它发挥作用有一段时间了。

令人沮丧。

编辑:

如果您想读取该文件并将\n文本中的 替换为实际的 EOL。您可以简单地使用:

Scanner sc = new Scanner(new File("/home/alain/Bureau/ttt.txt"));

//loop over real EOL
while(sc.hasNextLine()){

     //Replace the `\n` in the line with real EOL.
     System.out.println(sc.nextLine().replace("\\n", System.getProperty("line.separator")));
}
Run Code Online (Sandbox Code Playgroud)