File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes Inserting text to a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Inserting text to a file" Watch "Inserting text to a file" New topic

Inserting text to a file

shaleen kumar

Joined: Nov 01, 2002
Posts: 1
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();
String st = "\n<ROWSET>\n";
byte buff[] = st.getBytes();
Michael Zalewski
Ranch Hand

Joined: Apr 23, 2002
Posts: 168
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

Joined: Apr 23, 2002
Posts: 168
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.
I agree. Here's the link:
subject: Inserting text to a file
It's not a secret anymore!