Search and Replace

Home » Search and Replace » Java » Search and Replace

Sometimes you just need to search all files in a folder and replace everything that matches to a regular expression. Here is a program that does this trick. Of course you need to update the regular expression and other constants with values that meet your requirements. ATTENTION: This program can (depending on the values you assign to the constants) screw up any/all of your files, so make yourself a favor before running it: backup the files under the target folder.

[code language=’java’] import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Searches and replaces text on files of a folder and subfolders
* based on a regular expression. It’s capable of replacing
* subsequences that include several lines, thing Eclipse’s search
* and replace feature doesn’t do well.
*
* @author Ivan Alencar
* @author $Author: Ivan Alencar $
* @version $Revision: 1.0 $
*/
public class SearchAndReplaceText
{
/** Project folder */
private static final String PATH = "C:/target_path/";

/** File extensions to process */
private static final String[] EXTENSIONS = {"java", "jsp", "js"};

/** Regex will depend on what you want to replace */
private static final String REGEX = "(\/|n){1}\*n(.|\s|n)*?\*\/";

/** Replace by */
private static final String REPLACE_BY = "";

/** Pattern corresponding to the regular expression */
private static Pattern p = Pattern.compile(REGEX);

/** List of updated files */
private static List<String> updatedFileList = new ArrayList<String>();

/**
* Main method
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException
{
try
{
new SearchAndReplaceText().processDirFiles(PATH);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}

System.out.println();
System.out.println("*** UPDATED FILES ("+ updatedFileList.size() +") ***");
for(String fileName : updatedFileList)
System.out.println(" –>"+ fileName);
}

/**
* Recursively processes all the files under the directory
* specified.
*
* @param dir
* @throws IOException
*/
public void processDirFiles(String dir) throws IOException
{
System.out.println("Processing directory "+ dir);
File directory = new File(dir);
String[] fileNames = directory.list();

for(String fileName : fileNames)
{
File f = new File(dir +"/"+ fileName);
if(f.isDirectory())
processDirFiles(f.getPath());
else
{
if(isExtensionValid(f.getName()))
verifyFile(f);
}
}
}

/**
* Determines whether a file name is among the desired
* ones by extension. Vide EXTENSIONS array.
*
* @param name
* @return
*/
private boolean isExtensionValid(String name)
{
String extension = name.substring(name.lastIndexOf(‘.’) + 1);
return (Arrays.binarySearch(EXTENSIONS, extension) >= 0);
}

/**
* Determines whether a file contains the sequence determined by
* the regular expression, if so, replaces it and updates
* the file.
*
* @param f
* @throws IOException
*/
private void verifyFile(File f) throws IOException
{
System.out.println(" Verifying file "+ f.getName() +"…");

FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);

String line = "";
StringBuilder text = new StringBuilder();
while((line = br.readLine()) != null)
{
text.append(line);
text.append(‘n’);
}

br.close();

// Matches file text against the regular expression
Matcher m = p.matcher(text);

// Replaces the first occurrence
if(m.find())
{
text.replace(m.start(), m.end(), REPLACE_BY);
updateFile(f, text);
}
}

/**
* Updates the specified file with the specified text.
*
* @param f
* @param text
* @throws IOException
*/
private void updateFile(File f, StringBuilder text) throws IOException
{
System.out.print("Updating file "+ f.getName() +"…");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);

bw.write(text.toString());
bw.flush();
bw.close();
System.out.println("[OK]");
}
}
[/code]

Leave a Comment