开发者

Replacing string in a file with another string

What is the fastest way to do a search and replace on a string in an existing file using Java?

Let's say I have this:

// This references an existing file 
File file = ...

The file in question looks like this:

The Green Dog is furry.
It likes to run in the Green Grass.
Green is its favorite color.

How would I go about replacing the String "Green" with "Blue" and having that file re-saved with the new color?

Update: I've thought about this a little more and perhaps the best and fastest way is to just read the cont开发者_如何学JAVAents of the file into a string (using something like FileUtils) and then just doing a replace and re-writing to the file?


Have a look at Retrieving and Replacing number in text file which is pretty much the same.

Edit: Regarding your update, I would just use BufferedReader and BufferedWriter and leave it to the JVM to optimise reads/writes, i.e. I would do the replacements in a streaming fashion. Your suggested solution of reading to memory could be a bit faster - but I wouldn't read everything in memory (makes approach not scalable) unless there's a very good reason.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜