aspose file tools*
The moose likes Beginning Java and the fly likes How to replace a line in a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to replace a line in a file" Watch "How to replace a line in a file" New topic
Author

How to replace a line in a file

A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 978
Hi,

How do we replace a line in a file......

I have a if(condition)

When reading a file ,if the condition is true replace a line in the file

else

continue....



Regards
John Melton
Ranch Hand

Joined: Aug 17, 2004
Posts: 49
One problem with your current code is you are trying to overwrite the file every time.
Essentially, here's the steps you'll need to take
1. Open the input file A
2. Create an output file B
3. Loop over every line in A
a. If it DOES NOT start with "Page", write the current line to file B
b. If it DOES start with "Page", create your string buffer and write that to file B instead of the current line.

This should work based on your current design. You could do some performance tweaks to make it work better, but this should get you there.
Hope this helps.


[url]www.jtmelton.com[/url]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
This FAQ Page has some more hints about safely replacing an existing 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: http://aspose.com/file-tools
 
subject: How to replace a line in a file
 
Similar Threads
read chunks instead of lines with bufferReader
How to merge two files keeping leading blank spaces
FileIO
Write File to Harddrive
Removing prolog from an XML file