gpt4 book ai didi

java - 如何让Scanner正确读取转义字符?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:31 24 4
gpt4 key购买 nike

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

Hello World!\nI've been trying to get this to work for a while now.\nFrustrating.\n

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

Scanner input = new Scanner(new File(fileName));
String str = input.nextLine();
System.out.print(str);

现在,我希望输出为:

Hello World!
I've been trying to get this work for a while now.
Frustrating.

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

我认为 Scanner 能够正确读取转义字符,但它却像\\n 一样将其复制到字符串中。

最佳答案

如果 \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());
}

输出:

Hello World!

I've been trying to get this to work for a while now.

Frustrating.

编辑:

如果你想读取文件并将文本中的 \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")));
}

关于java - 如何让Scanner正确读取转义字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10830366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com