如何使扫描仪正确读取转义字符? [英] How to make Scanner Properly Read Escape Characters?

查看:139
本文介绍了如何使扫描仪正确读取转义字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取一行中读取所有内容的文件:

I'm reading from a file that reads something like all on one line:

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

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

And my Scanner reads that from the file and puts it in a String:

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都包含在输出中,并且所有内容都在一行而不是单独的行。

But instead I'm getting the exact same thing as the input. That is, each \n is included in the output and everything is on one line instead of separate lines.

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

I thought that Scanner would be able to read the escape character properly but it's instead copying it onto the String like it's \\n.

推荐答案

如果 \\ \\ n 写的是你不能使用的文件 nextLine()因为没有 \ n (行尾)但是 \\ n (两个字符)。

If \n is written is the file you can't use nextLine() because there is not \n (end of line) but instead there is \\n (two characters).

请尝试使用分隔符:

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

输出:


Hello World!

Hello World!

我一直想让它工作一段时间。

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

令人沮丧。

编辑:

如果你想要读取文件并用实际的EOL替换文本中的 \ n 。您只需使用:

If you want to read the file and replace the \n in the text with actual EOL. You can simply use :

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")));
}

这篇关于如何使扫描仪正确读取转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆