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);
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 \n 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.
You can use
Scanner.useDelimiter
to set your own delimiter. In your case using double quoted\\n
:Example:
Outputs:
If
\n
is written is the file you can't usenextLine()
because there is not\n
(end of line) but instead there is\\n
(two characters).Instead try with a delimiter :
Output :
EDIT:
If you want to read the file and replace the
\n
in the text with actual EOL. You can simply use :No,
Scanner
won't do that for you. You'll have to do the translation yourself.(Note that if you use something like
sc.useDelimiter("\\\\n")
as others have suggested you're breaking the functionality of the ordinarynext()
method andnextLine()
may not function as expected.)Here's a sketch of how I would solve it:
Change
to
where
JavaEscapeReader
would extendFilterReader
like this:Given an input file with the content
the program
prints
Another option is to use
StringEscapeUtils.unescapeJava
and post process the read strings.