Hi all,

Here is what i found with google to Find and Replace word in Java:

public class ReplaceAll {

    public static void main(String[] args) {
        String str="We want replace replace word from this string";

        str=str.replaceAll("replace", "Done");

        System.out.println(str);
    }
}

It works well but how to do the same with a known file text?
This task was asked by my favorite idiot chief as a work.

Thank you very if someone could help me.

well ... you read your file, store the contents (for example) in an ArrayList.
then, you iterate over that list and you perform the replaceAll method on the elements of this list.

afterwards, you can store the contents in that arraylist back into the file.

but, if I were you, I would keep from referring to your boss or employer as 'my favorite idiot chief'.
1. there's no need to insult people
2. expecting you to have enough understanding of java to be able to perform this task yourself, is quite normal
3. please do realize, that, even if he were the biggest idiot around, chances of him being able to use the internet and google are propably larger than 0. comments like this have led to numerous people getting fired already, no reason to cause one more, I would say.

Ok thank you for your advice,
i love my chief.

I tried this:
package findnreplace;

import java.io.File;

public class FindNReplace
{
  public static void main(String args[])
  {
   String[] files = { "file1.txt", "file2.txt", "file3.txt" };
for (String file : files)
{
    File f = new File(file);
    String content = FileUtils.readFileToString(new File("filename.txt"));
    FileUtils.writeStringToFile(f, content.replaceAll("hello", "world"));
 }
 }
}

And i have this error:
run:
Exception in thread "main" java.lang.UnsupportedOperationException: Not yet implemented
at findnreplace.FileUtils.readFileToString(FileUtils.java:17)
at findnreplace.FindNReplace.main(FindNReplace.java:13)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

What library do i have to add?

Thank you

Well ....
if you want to use the FileUtils class, you'll have to add the jar file which contains it to your classpath. just take a loot at this to learn more about that class.

you'll need to use the common-io package, and you'll have to catch and handle the exceptions thrown by the methods you're calling.

but there are other ways to read and write files using java, the java tutorials provided by Oracle can help you out as well. just take a look at this.

it's complicated for me. but thank you

have you worked with java before?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.