This content has been marked as final. Show 7 replies
Read the text in find the line you want to change change it then write it back out
You can't really do this mostly.
If you have liines of fixed lengths then you can do this with RandomAccessFile. Otherwise you cannot. Filesystems do not work this way. You cannot arbitrarily inject or remove bytes from the middle of a file. You can replace them but that''s usually unhelpful.
You must rewrite the entire file replacing the line you want with your new one.
Read the file. Replace the line (in the data that you have in memory). Write the data back down to disk.
can we use FileInputStream and FileOutputStream concepts to replace the line here?
Sure. Create a new output file. Then copy the lines up to the line needing replaced, insert the replacement, and copy the following lines. (Use a BufferedReader).
Then delete or rename to old file, and rename the new file to the old one's name.
use this thing:
open the file,
read its contents, replace the text you need in the contents, set the contents back into the file.
it takes care of the IO for you.
Swallowing the whole file is slightly grotty. First off, that limits your file size. Second, if you get an IO error (e.g. disk full), or the program otherwise crashes during the write then you can lose the file.
Using file generations is safer, and can deal with huge files without using huge amounts of memory.