Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Inserting text to a file

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
 
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic