Click here to Skip to main content
15,886,049 members
Articles / Programming Languages / Java / Java SE / J2EE
Tip/Trick

FindReplace

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
22 Oct 2015CPOL2 min read 10.5K   1
This article explains how to develop a custom Java utility to find and replace strings in multiple files in one go

Introduction

In our day to day development there are times where we need some custom utlities which does some repetative task, nothing but an automation. In this article we will see a simple utility developed using Java to find and replace strings in multiple files in a single run.

The Program

Lets classify this utility development into three blocks.

  • Backup creation for the files

    In this utility first we will create a backup of all the files under the subfolder, backup.
  • Find and Replace Map Creation

    We need to create a map from .CSV file which contain find and replace strings
  • Using the map created in before step we will find string in file replace that string in file.

Now let us get into details of each block of code

Creating a Backup

Let us assume that our files to process are in D:\FindReplace. Now this will be our source folder path.

Java
String sourceFolderPath = "D:\\FindReplace";

Our backup location would be D:\FindReplace\backup. And I am assuming that even CSV is loacted in same folder i.e., D:\FindReplace and now our utlity will output the replaced files in D:\FindReplace\ReplacedFiles.

Java
String sourceFolderPath = "D:\\FindReplace";
String destFolderPath = sourceFolderPath + "\\ReplacedFiles";
String findReplaceCSV = sourceFolderPath + "\\findReplace.csv";

Now let us start our backup creation. To create a backup we need to iterate over each file and copy the file into sourceFolderPath\backup folder with same filename and .bak extension. Below is the snippet for the same action

Java
System.out.println("*****Backup Intialized******");
Java
  if(file.isFile()) { 
     String sourceFilePath = file.getAbsolutePath(); 
     String bakFilePath = sourceFilePath.substring(0,sourceFilePath.lastIndexOf(File.separator)) +
                          "\\backup\\" + 
                          file.getName().replace(sourceFilePath.substring(sourceFilePath.lastIndexOf("."), 
                          sourceFilePath.length()), ".bak");   
     File backupFile = new File(bakFilePath);   
     createBackup(file, backupFile);      
  } 
}   
System.out.println("****Backup Completed*****");         

The above code calls the 'createBackup()' method which actually does the copy action. This method takes in two File arguments, one is source and other will be target. Below is the code snippet for the method.

Java
public static void createBackup(File source, File target) throws IOException{
        InputStream in = new FileInputStream(source);
        OutputStream out = new FileOutputStream(target);
       
          byte[] buf = new byte[1024];
          int len;
     
          while ((len = in.read(buf)) > 0) {
              out.write(buf, 0, len);
          }
     
          in.close();
          out.close();
    }

This Completes the first module. Now let us see find and replace map creation from .CSV file

FindReplace Map

We need to create a map collection from CSV file which contain find and replace string. Here we will store find strings in CSV a key in map and corresponding replace string will be stored as value for the key. Below is the snippet for the action

Java
Map<String, String> findReplaceMap = new HashMap<String, String>();
        
        System.out.println("****Find Replace Map Creation Started****");
        
        findReplaceMap = createReplaceMap(findReplaceCSV);
        
        System.out.println("****Find Replace Map Created!*****");        

The above snippet calls createReplaceMap() method which takes in string parameter as argument, this string will be CSV file location and this method reads in CSV and creates map and returns the map collection.

Java
public static Map<String, String> createReplaceMap(String csvfileName){
        Map<String, String> _findReplaceMap = new HashMap<String, String>();
        BufferedReader br = null;
        try {
            String line = "";
            String cvsSplitBy = ",";
            br = new BufferedReader(new FileReader(csvfileName));
            while ((line = br.readLine()) != null) {
                
                // use comma as separator
                String[] findReplace = line.split(cvsSplitBy);

                _findReplaceMap.put(findReplace[0], findReplace[1]);

            }
            br.close();
        
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return _findReplaceMap;
        
    }
This completes the second module findReplace map creation. Now the final module, and main action find the stirng in file and replace the string. For this action we iterate read each file programatically and search for the map key values, if a value is found replace it with corresponding value. We use replace() method for this action.
Below is the snippet for the same.
Java
System.out.println("*****Find Replace in Files Intialized******");
System.out.print("Find Replace in progress");
for(File file:listOfFiles){
    if(file.isFile()){

        System.out.print(".");

        File convFile = new File(destFolderPath + @"\" + file.getName());
        try {
            convFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        findReplace(file, convFile, findReplaceMap);
    }
}
System.out.println("");
System.out.println("****Find Replace Action Completed******");

The above code call a method findReplace() for the actual action this method takes in three arguments, first two will be file arguments, source file and converted file, the third argument will be findReplace map. Below the snippet for the method.

Java
public static Map<String, String> createReplaceMap(String csvfileName){
    Map<String, String> _findReplaceMap = new HashMap<String, String>();
    BufferedReader br = null;
    try {
        String line = "";
        String cvsSplitBy = ",";
        br = new BufferedReader(new FileReader(csvfileName));
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] findReplace = line.split(cvsSplitBy);

            _findReplaceMap.put(findReplace[0], findReplace[1]);

        }
        br.close();

    }
    catch(Exception e){
        e.printStackTrace();
    }

    return _findReplaceMap;
}

History

This is the first revision of the article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student SNIST
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHave you consider to post this as a tip? Pin
Nelek22-Oct-15 22:52
protectorNelek22-Oct-15 22:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.