Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

java - How to make Scanner Properly Read Escape Characters?

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

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

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

Now, I want the output then to be:

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Instead try with a delimiter :

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

Output :

Hello World!

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

Frustrating.

EDIT:

If you want to read the file and replace the 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 `
` in the line with real EOL.
     System.out.println(sc.nextLine().replace("\n", System.getProperty("line.separator")));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...