Simon Corcos
Simon Corcos

Reputation: 1022

InputStreamReader reads 13 and 10 for carriage return. Why?

I'm using the FileInputStream.read() method to parse a text file in the context of a homework on the Huffman algorithm.

My text file goes like this (the numbers are just line numbers) :

1.
2.s
3.
4.

The return of the read() method is respectively:

13,115,10,10

And when I write these back in another text file with an FileOutputStream, the newline characters don't do a newline.

Why is the first line's newline character always 13 and the other ones 10?
Am I using the correct classes or should I use different stream readers?
Why don't the newline characters do a newline when I write them back into a file?

UPDATE!

Ok sorry about that, the reading is not a problem.

First, here is some code :

FileOutputStream fos = new FileOutputStream(fileOut);
fos.write(115); //s
fos.write(13);  //newline
fos.write(115); //s
fos.write(10);  //newline
fos.write(10);  //newline

When I open the file in notepad I see :

1.ss
2.

I guess I have to do something to the int variables (or constants in this case) but I don't know what.

Upvotes: 0

Views: 805

Answers (2)

Both carriage return ("\r", CR, ASCII 13) and line feed ("\n", LF, ASCII 10) are valid line endings, and are the conventions used on old Macintoshes and Unixes respectively.

Windows uses carriage return followed by linefeed ("\r\n", CRLF, ASCII 13, 10).

See Wikipedia: http://en.wikipedia.org/wiki/Newline

The person who created the text file might have used different line endings either deliberately, or accidentally by editing the file on operating systems with different line ending conventions.

If you want to read the file as lines, you might want to use a BufferedReader wrapping an InputStreamReader:

Reader in = new BufferedReader(new InputStreamReader(fileInputStream, encoding));

in.readLine();

Upvotes: 1

Ingo
Ingo

Reputation: 36339

The point is you ought to read this as text (for example, reading line by line with a BufferedReader), not binary.

If you print

"\rx\n" (or the equivalent with numbers)

it should indeed do a line feed, but programs like Windows Notepad will not recognize the single \n.

To analyze such cases, you probably want a hex editor.

Upvotes: 0

Related Questions