• Post Reply Bookmark Topic Watch Topic
  • New Topic

string to be replaced in a file

 
ramjcp kris
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

i want to replace a old string with new string in a file.
i have written all the necessary code,its working fine.
but i have used a temp file into which i will read my original file line by line and search for the string and modify it and writing into temp file.
Is there any way where instead of creating a temporary file,i can modify the same file while reading it.
please help me with any sample code....
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15715
73
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the new string that you're replacing the original string with are exactly the same length, you might be able to do it by using java.io.RandomAccessFile.

If the new and old strings are not the same length, there's no other / better way than how you already implemented it.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I drag this old chestnut out every once in a while, so apologies to the regulars ... Something I borrowed from IBM's VM/CMS operating system:

* read original
* write temp
* rename original to backup
* rename temp to original
* erase backup

This gives you really safe coverage. If any of the operations fail you still have the original data.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!