tags:

views:

63

answers:

2

If I have a a textfile say file.txt and it contains random words like:

fruit:apple
fruit:orange
fruit:grape

In java, if i wanted to change the second line to read fruit:pear how could i do it? I know how to append onto the end of a txt file like so:

BufferedWriter wrtr = new BufferedWriter(new FileWriter(file.txt, true));
wrtr.write("blahblah");  //appends

but this is not what i want, i just want to be able to edit a string in the file in a certain position. any ideas?

A: 

Files are just bits on disk.

Your file actually looks like this (give or take encodings & platform specific stuff):

fruit:apple\nfruit:orange\nfruit:grape

so if you want to 'edit' part of it, everything from that point onwards needs to be manipulated.

You could play with offsets, working on the byte level, but realistically for data without fixed field lengths etc., the simplest approach would be to rewrite the whole file.

Brabster
+1  A: 

You can read/write a text file as outlined here. Once you read the content, you can do a String.replaceAll("fruit:orange", "fruit:pear") and write the new content into the file.

Tomislav Nakic-Alfirevic
That could work but will not work if that line appears multiple times.
Paul