This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
When you make a string with "\n" in your source code, the compiler sees the backslash as an escape character to indicate something special will follow. It translates the \n into some combination of 0x000D and 0x000A depending on the OS.
When you put the characters backslash and n into a data file they are really those characters. If you want to turn them into newlines, you'll have to replace "\n" with a newline.
Take a deep breath; this gets confusing. The JDK 1.4 and later String.replace uses regular expressions. To put a backslash in an expression you have to escape it with another backslash: \\n. And to put a backslash in a Java string you have to escape it with another, so we get "\\\\n" to match the characters in your file. Try this:
lineIn = lineIn.replace("\\\\n", "\n");
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
lineIn = lineIn.replace("\\\\n", "\n"); plz can you explain more ,by a code if you can
Joined: Jan 29, 2003
A slight mod to your code ...
See what that does.
First argument: Java sees \\ and replaces it with \, giving four characters "\\\n". It sees another \\ and replaces it with \ giving three characters "\\n". This is the regular expression passed to replace(). The regex interpreter sees \\ and replaces it with \ giving two characters "\n". It looks for these two characters in the input.
Second argument: Java sees "\n" and replaces it with the newline character.
So replace() replaces the two characters "\n" with the newline character.
If you got all that, take the afternoon off, go have a beer.
If you read a text file in a texteditor and you can see \n in that text, it does not mean that if you read that file using java that it will read a linefeed character. No, it will actually read 2 characters a "\" (backslash) and a "n". If you want the file to be separated using linefeeds you actually have to put a real linefeed in there (RETURN) between the lines.
If you want to use the "\n" as line separator you will have to do some post processing after you have read the data and replace all "backslash-n" Strings with linefeed characters ('\n').