new line in Random Access File in java

14,041

Solution 1

Try this:

 RandomAccessFile file = new RandomAccessFile("e:\\demo.txt","rw");
 String originalString = "First line \nSeconf line \n";
 String updatedString = originalString.replace("\n","\r\n");
 file.writeBytes(updatedString);

Solution 2

You can write a line separator. In order to get the correct line separator for the currently running operating system, you'll have to look for the line.separator property. Something along these lines:

randomAccessFile.writeBytes(System.getProperty("line.separator"));
Share:
14,041
aceBox
Author by

aceBox

Updated on June 04, 2022

Comments

  • aceBox
    aceBox almost 2 years

    Whenever using the 'writeBytes' method of RandomAccessFile in java,it writes the text in the same line in the file. How can I get to a new line with RandomAccessFile only? (No BufferedReader).

    • sudmong
      sudmong over 11 years
      that is what javadoc says "The write starts at the current position of the file pointer". try writing new line character before writing data.
  • aceBox
    aceBox over 11 years
    Basically using '\r\n' escape sequence worked with it.Thanks a lot,friend!!
  • tom_mai78101
    tom_mai78101 over 9 years
    Your method is wrong. write() does not take in String. You should probably change it to writeChars(). Another way is randomAccessFile.writeBytes(System.getProperty("line.separat‌​or"));, since writeBytes() can take in String as a parameter.
  • Marc Baumbach
    Marc Baumbach over 9 years
    @tom_mai78101 Thanks, fixed it.