The moose likes Beginning Java and the fly likes Code to Modify the contents of a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Code to Modify the contents of a file" Watch "Code to Modify the contents of a file" New topic

Code to Modify the contents of a file

Moni Marva

Joined: Jan 24, 2005
Posts: 23
The contents of the .log file are as mentioned below,


In this I want to change the status from say "failure" to "sucess" for a particular line.
I want the solution to do this using File Io , Random Access file.
sandip mense

Joined: Oct 14, 2003
Posts: 28

These are the steps that you need to follow,

Load the file from the file system.
Open the file in read/write mode.
Read the line into a StringBuffer.
Get the length of the string that you want to replace
Replace the String using the StringBuffer replace(startindex, endindex, Stringtoreplace) method

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
With RandomAccess you can locate a string in a file and overwrite it with something else of exactly the same length. Since "failure" and "success" both have 7 letters you could do it in place. The "locate" part might be a little challenging, though, since there's no API to read one line at a time from RandomAccess.

With ordinary file io you can read the input one line at a time, examine each line, make the change when you find the target, and write a new file one line at a time. I like this trick to be very safe when rewriting a file:

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Code to Modify the contents of a file
It's not a secret anymore!