2

How to use regular expressions in a file content. i am having group of files, i want to search a string in all the files and replace in all the files.

can anybody help me in this? the cose is below:

package com.java.far;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll {

    public static void main(String[] args)throws IOException {

        Runtime r=Runtime.getRuntime();
        System.out.println(r.freeMemory());

        String path="D:\\JOBRELATED\\FAR";
        String files;
        File folder=new File(path);
        File[] listofFiles=folder.listFiles();
        for (int i = 0; i < listofFiles.length; i++) {
            if (listofFiles[i].isFile()) {
                files=listofFiles[i].getName();
                if(files.endsWith("tex")){
                System.out.println(files);

                BufferedReader br=new BufferedReader(new FileReader("D:\\JOBRELATED\\FAR\\"+files));
                String line;
                while((line=br.readLine())!=null){
                Pattern p=Pattern.compile("Diamond in History and Research");
                Matcher m=p.matcher(line);
                int count=0;
                while (m.find()) {
                    count++;
                    //System.out.println(m.start() +"\t"+ count);
                    System.out.println(line);
                    m.replaceAll("abc");


                }
                }

            }
            }
        }


    }
}
2
  • Is it not possible to just use sed? ahh... looks like you're on Windows box. Commented Aug 9, 2012 at 5:26
  • Please note that regexps do not work on large files. Regexps in their nature are recursive, and in case when you're processing large block of data with regexp you get StackOverflow exception. Commented Aug 9, 2012 at 6:09

1 Answer 1

3

Looks like you're on the right track; I don't know of a framework that will find & replace within a file. I have put some other tips below which you could review.

Your final step which you're missing is to add a OutputWriter, or similar outputter. Once you've read the file contents, check it contains the match & replaced it, you should do a boolean check whether a change was made. If so, output the file.

Other comments: 1. You won't need to do a listofFiles[i].isFile() if you're using .listFiles() 2. Compile your pattern outside of the for loop for efficiency. 3. Use a dynamic for loop, might make it easier: for(final File file : listofFiles)

Example:

   final File[] files = new File(".").listFiles();
   final Pattern pattern = Pattern.compile(".*a.*");
   for(final File file : files) {
       System.out.println(file.getName());
       final BufferedReader reader = new BufferedReader(new FileReader(file));
       final StringBuilder contents = new StringBuilder();
       while(reader.ready()) {
           contents.append(reader.readLine());
       }
       reader.close();
       final String stringContents = contents.toString();
       if(stringContents.toString().matches(".*a.*")) {
           stringContents.replaceAll("a", "b");
           final BufferedWriter writer = new BufferedWriter(new FileWriter(file));
           writer.write(stringContents);
           writer.close();
       }
   }
Sign up to request clarification or add additional context in comments.

3 Comments

Sample updated above. In that I'm not using Pattern or Matcher, you can decide which way to use it. BOth are good, Pattern & Matcher probably better.
You shouldn't need to. If you're replacing the contents in the original file, and updating the file (as in, overwriting), just using the File object should be fine.
when i am running this the output is: 4989944 .classpath .project .settings Exception in thread "main" java.io.FileNotFoundException: .\.settings (Access is denied) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileReader.<init>(Unknown Source) at com.java.far.ReplaceAll.main(ReplaceAll.java:20)

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.