开发者

Java File I/O - Text File - how to edit something?

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 posit开发者_开发问答ion. any ideas?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜