amitjavaranch amitjavaranch
Greenhorn
Posts: 1
Hi,

I have a problem reading a txt file. An example string from the file is: "amit\nkumar".

Actual Output :
"amit\nkumar"

Expected Output :
"amit
kumar"

Why is this so?

The code is the following:

new FileInputStream(filename));
}

Any hints what is going wrong? It must be something with the input stream, since writing the String directly into the code works.

Amit Kumar

Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
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");

nana Amr
Ranch Hand
Posts: 53
lineIn = lineIn.replace("\\\\n", "\n");
plz can you explain more ,by a code if you can

Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
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.

Manuel Moons
Ranch Hand
Posts: 229
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').