Inserting text in middle using RandomAccessFile removes some text after that

java, java-io

Solution

`RandomAccessFile`

A random access file behaves like a large array of bytes stored in the file system.

In fact it does not care about shifting the array elements in the case of write operations (only the pointer is advanced). Such an operation overwrites existing values:

Output operations write bytes starting at the file pointer and advance the file pointer past the bytes written.

Problem

My Sample Code ``` String line = null; RandomAccessFile file = new RandomAccessFile("D:/mahtew.txt", "rw"); System.out.println(file.getFilePointer()); while((line = file.readLine()) != null){ System.out.println(line); System.out.println(file.getFilePointer()); if(line.contains("Text to be appended with")){ file.seek(file.getFilePointer()); file.write(" new text has been appended".getBytes()); break; } } file.close(); ``` demo.txt before execution ``` one two three Text to be appended with five six seven eight nine ten ``` demo.txt after execution ``` one two three Text to be appended with new text has been appendedten ``` Also i tried using setLength to change length of file before new text is appended. But still some text is getting trimmed from output file. Any help will be appreciated Thanks Mathew

Original source