views:

316

answers:

3

I'm trying to write a program that manipulates unicode strings read in from a file. I thought of two approaches - one where I read the whole file containing newlines in, perform a couple regex substitutions, and write it back out to another file; the other where I read in the file line by line and match individual lines and substitute on them and write them out. I haven't been able to test the first approach because the newlines in the string are not written as newlines to the file. Here is some example code to illustrate:

String output = "Hello\nthere!";
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("test.txt"), "UTF-16"));

System.out.println(output);
oFile.write(output);
oFile.close();

The print statement outputs

Hello
there!

but the file contents are

Hellothere!

Why aren't my newlines being written to file?

+6  A: 

You should try using

System.getProperty("line.separator")

Here is an untested example

String output = String.format("Hello%sthere!",System.getProperty("line.separator"));
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("test.txt"), "UTF-16"));

System.out.println(output);
oFile.write(output);
oFile.close();

I haven't been able to test the first approach because the newlines in the string are not written as newlines to the file

Are you sure about that? Could you post some code that shows that specific fact?

Tom
Well part of it is that I only know how to read a file in one line at a time, so the newlines I was providing *were* getting written out, but only as LF, not CRLF, and weren't displaying correctly in Notepad, as kd304 pointed out.
Cristián Romo
+1  A: 

Use System.getProperty("line.separator") to get the platform specific newline.

Nate
A: 

Consider using PrintWriters to get the println method known from e.g. System.out

Thorbjørn Ravn Andersen