1

There are many posts about this but I couldn't find one working correctly For Example below code works but it deletes the first line.

I want to insert some text at the beginning of a file without deleting anything, just an insert. Is that possible?

RandomAccessFile f = new RandomAccessFile(new File("myFile.txt"), "rw");
f.seek(0);
f.write("Blah Blah This is first line".getBytes());
f.close();

I also tried this, still deletes the first 12 bytes

Spring
  • 11,333
  • 29
  • 116
  • 185
  • 1
    use the code you posted, but first read in the line and add that to the text you are inserting before writing it back to the file – Hrqls May 27 '14 at 09:58
  • @Hrqls tnx Coudl you briefly show it in an example as anwer? – Spring May 27 '14 at 09:59

1 Answers1

2

Pseudocode is

String existing = Read whole content of file. 

String newcontent = "Blah Blah This is first line" + existing

f.write(newcontent);      
Deepu--Java
  • 3,742
  • 3
  • 19
  • 30
Manish Mudgal
  • 1,166
  • 1
  • 9
  • 24
  • 1
    Yup. File systems don't generally support inserting data in-between or at the beginning of the file. Appending to the end is supported though. – Toni May 27 '14 at 09:57