Pavan Patidar
Pavan Patidar

Reputation: 373

How to write new line in Java FileOutputStream

I want to write a new line using a FileOutputStream; I have tried the following approaches, but none of them are working:

encfileout.write('\n');
encfileout.write("\n".getbytes());
encfileout.write(System.getProperty("line.separator").getBytes());

Upvotes: 21

Views: 66031

Answers (5)

Raksha Bhangale
Raksha Bhangale

Reputation: 1

You can use Fos.write(System.lineSeparator().getBytes()). it worked for me.

Upvotes: 0

Teddy
Teddy

Reputation: 4223

It could be a viewer problem... Try opening the file in EditPlus or Notepad++. Windows Notepad may not recognize the line feed of another operating system. In which program are you viewing the file now?

Upvotes: 10

vinter
vinter

Reputation: 520

To add a line break use

fileOutputStream.write(10);

here decimal value 10 represents newline in ASCII

Upvotes: 4

user3736908
user3736908

Reputation: 53

String lineSeparator = System.getProperty("line.separator");
<br>
fos.write(lineSeparator.getBytes());

Upvotes: 4

AlexR
AlexR

Reputation: 115328

This should work. Probably you forgot to call encfileout.flush().

However this is not the preferred way to write texts. You should wrap your output stream with PrintWriter and enjoy its println() methods:

PrintWriter writer = new PrintWriter(new OutputStreamWriter(encfileout, charset));

Alternatively you can use FileWriter instead of FileOutputStream from the beginning:

FileWriter fw = new FileWriter("myfile");
PrintWriter writer = new PrintWriter(fw);

Now just call

writer.println();

And do not forget to call flush() and close() when you finish your job.

Upvotes: 20

Related Questions