简体   繁体   中英

new line in Random Access File in java

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 ).

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"));

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);
System.getProperty("line.separator");

尝试在文件之前写入新行,因为它将开始写入上次停止写入的位置。

new line character has an ASCII value of 10 . You can store this value in in a Byte and then use the "writeBytes" which will result in a new line.

String data = "New Line";
RandomAccessFile raf = new RandomAccessFile(myFile);
raf.writeBytes("\r\n" + data);

This will add a new line (windows style / CRLF) before the "text".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM