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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.