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"));
Author by
aceBox
Updated on June 04, 2022Comments
-
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 withRandomAccessFile
only? (NoBufferedReader
).-
sudmong over 11 yearsthat is what javadoc says "The write starts at the current position of the file pointer". try writing new line character before writing data.
-
-
aceBox over 11 yearsBasically using '\r\n' escape sequence worked with it.Thanks a lot,friend!!
-
tom_mai78101 over 9 yearsYour method is wrong.
write()
does not take inString
. You should probably change it towriteChars()
. Another way israndomAccessFile.writeBytes(System.getProperty("line.separator"));
, sincewriteBytes()
can take inString
as a parameter. -
Marc Baumbach over 9 years@tom_mai78101 Thanks, fixed it.