19

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());
Edd
  • 3,510
  • 3
  • 23
  • 33
Pavan Patidar
  • 243
  • 1
  • 2
  • 9
  • Define "not working". – Christoffer Hammarström Jun 16 '14 at 12:09
  • its not writing new line – Pavan Patidar Jun 16 '14 at 12:12
  • @PavanPatidar: It is writing a newline. For sure. – Martijn Courteaux Jun 16 '14 at 12:13
  • 2
    Try executing encfileout.write("Fant".getbytes()); encfileout.write("\n".getbytes()); encfileout.write("astic".getbytes()); If you see the whole word on a single line your problem is confirmed. Especially, the encfileout.write(System.getProperty("line.separator").getbytes()); should work. – Teddy Jun 16 '14 at 12:16
  • @Teddy it is working on localhost but when i am deploying in on my server it does't works. – Pavan Patidar Jun 16 '14 at 13:11
  • It could be a viewer problem... Try opening the file in EditPlus or Notepad++. Windows Notepad may not recognise line feed of another operating system. In which program are you viewing the file now? – Teddy Jun 16 '14 at 13:44
  • @Teddy:Thanks, you are right its viewing problem, notepad++ is showing correctly my data. Thanks again for bring my attention. – Pavan Patidar Jun 16 '14 at 20:02
  • @PavanPatidar I added the last comment as an answer... you can accept if it solved your problem. If you accept it, this question will be marked as answered. – Teddy Jun 16 '14 at 20:22

4 Answers4

16

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.

Paolo Forgia
  • 5,804
  • 7
  • 39
  • 55
AlexR
  • 109,181
  • 14
  • 116
  • 194
10

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

Teddy
  • 3,534
  • 2
  • 29
  • 51
1

To add a line break use fileOutputStream.write(10); because decimal value 10 represents newline in ASCII

1
String lineSeparator = System.getProperty("line.separator");
<br>
fos.write(lineSeparator.getBytes());
Axe319
  • 2,760
  • 2
  • 8
  • 23
  • Please consider adding some form of explanation with your answer. Code only answers are typically discouraged. – Axe319 Oct 06 '20 at 17:32