New line in FileOutputStream

16,523

Solution 1

You should take care of managing crossplatform line separator, this can be retrieved in many ways:

  • System.getProperty("line.separator")
  • System.lineSeparator() (only Java7)
  • String.format("%n")

Then you should take care of using a DataOutputStream wrapped around your FileOutputStream, this because you will be allowed to choose many better methods like

  • writeChars(String str)
  • writeBytes(String str)
  • writeUTF(String str)

so that you will use the most suitable for your situation.

Mind also that writing a byte array directly on the stream creates binary data, which is somewhat opposite to using newlines (which are text instead).

Solution 2

On windows you need to use 13 and 10 as line separator (CR, LF) - i.e.:

os.write(13);
os.write(10);

Hence, if you want your app to be platform independent, you should use whatever is in the line.separator system property as Jack suggests.

Share:
16,523
nr5
Author by

nr5

Updated on June 27, 2022

Comments

  • nr5
    nr5 almost 2 years

    Ascii value of next line is 10. so i tried this...

     FileOutputStream os = new  FileOutputStream(f, true);
        os.write(10);  // this should get me to next line ?
        os.write(b);   // b is a byte array...
    
  • nr5
    nr5 almost 12 years
    Sir, this i know that if i wrap around with bufferedoutputstream or Dataoutputstream, i can easily go to next line... just wanted to know that if os.write(32);//space is working then why not 10*
  • Jack
    Jack almost 12 years
    Which operating system are you using?