This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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
Similar Threads
using the seek() method to prevent data overwriting in a text file
Database file reader
Image not displayed in JEditorPane
writing text file with RandomAccessFile
Memory Efficiency List -> String