• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inserting text to a file

 
shaleen kumar
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to insert text into a file at a specific location without overwriting the existing text .
Is that possible and if yes , how?
I am currently using RandomAccessFile class to achieve my objective.The snippet used by me is as follows but it overwrites which i dont want
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
String fLine = raf.readLine();
if(fLine.startsWith("<?xml"))
{
raf.seek(fLine.length());
String st = "\n<ROWSET>\n";
byte buff[] = st.getBytes();
raf.write(buff);
raf.close();
}
 
Michael Zalewski
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No easy way to do this (not in one line).
I would suggest using two files. Open an FileInputStream and a FileOutputStream. Copy from the FileInputStream to the FileOutputStream, and when you get to the offset you want, insert your extra String.
Then close the input and output, delete the input and rename the output.
 
Michael Zalewski
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or, if the file is small enough, just read the entire file into a StringBuffer. Manipulate the StringBuffer using StringBuffer.insert(), .delete() and .append(). Then write the StringBuffer back.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic