1

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 contents of the file into a string (using something like FileUtils) and then just doing a replace and re-writing to the file?

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
digiarnie
  • 22,305
  • 31
  • 78
  • 126
  • Not the same answer, but close http://stackoverflow.com/questions/3939561/how-can-this-java-code-be-improved-to-find-sub-string-in-a-string – zengr Feb 22 '11 at 01:02

1 Answers1

4

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.

Community
  • 1
  • 1
Lucas Zamboulis
  • 2,494
  • 5
  • 24
  • 27