How to write string replace java application

In this tutorial we are going to show you how to write string replace java application. This simple application is processing directories tree recursively and finds files with a given extension. For each file that has appropriate extension a processing is done – we find strings and replace it with other strings. String replace definition is held in a separate file and loaded at the beginning of the program.

It this string replace java application we are going to demonstrate following mechanisms:
-        Reading program agruments
-        Reading and writing files in java
-        Coping file bytes from one to another in java
-        Recursive files and directories processing in java
-        Using Map interface in java

Application code looks like this.

StringReplacerApp.java


package com.itcuties.java.tutorials;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Replaces file contents
 *
 * @author itcuties
 */
public class StringReplacerApp {
   // A map of strings where:
   // key represents a string to be replaced
   // value is a string to replace key with
   private static Map<String, String> replaceStrings;

   // Extension of a file that we are going to process .
   private static String fileExtension;

   // A sepparator used in a file that contains replace definitions.
   private static String SEPARATOR = "===>";

   // Load replace strings data.
   private static void loadReplaceData(String dataFile) throws IOException {
      System.out.println("Loading replace data from file " + dataFile);

      replaceStrings = new HashMap<String, String>();

      FileInputStream fstream = new FileInputStream(dataFile);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      String line;
      while ((line = br.readLine()) != null) {
         String[] lineSplit = line.split(SEPARATOR);
         System.out.println("reading replace: " + lineSplit[0] + " with:" + lineSplit[1]);
         replaceStrings.put(lineSplit[0], lineSplit[1]);
      }

      br.close();
      in.close();
      fstream.close();
   }

   // Process directory
   private static void processDirectory(File directory) throws IOException {
      System.out.println("Processing directory " + directory.getName());

      for (File node: directory.listFiles()) {
         if (node.isFile())
            processFile(node);
         else if (node.isDirectory())
            processDirectory(node);
      }
   }

   // Process file
   private static void processFile(File file) throws IOException {
      System.out.println("Processing file " + file.getName());
      // If a file has an appropriate extension then process it
      if (file.getName().indexOf(fileExtension) != -1) {
         // Reading objects
         FileInputStream fis = new FileInputStream(file);
         DataInputStream in = new DataInputStream(fis);
         BufferedReader br = new BufferedReader(new InputStreamReader(in));

         // Writing objects
         File tmpFile = new File(file.getAbsolutePath() + "_tmp");
         FileWriter fw = new FileWriter(tmpFile);
         BufferedWriter out = new BufferedWriter(fw);

         String line;
         while ((line = br.readLine()) != null) {
            for (String replaceKey: replaceStrings.keySet()) {
               if (line.indexOf(replaceKey) != -1)
                  line = line.replaceAll(replaceKey, replaceStrings.get(replaceKey));
            }
            out.write(line+"\n");
         }

         br.close();
         in.close();
         fis.close();

         out.close();
         fw.close();

         // Tmp file is ready now
         // Delete original file
         if (!file.delete())
            throw new IOException("Can't delete " + file.getName());
         if (!file.createNewFile())
            throw new IOException("Can't create " + file.getName());

         // Copy from _tmp to original file - we have to create it now
         copyFile(tmpFile,file);

         // Delete tmp file
         if (!tmpFile.delete())
            throw new IOException("Can't delete " + tmpFile.getName());
      }
   }

   // Copy from file to file.
   private static void copyFile(File src, File dest) throws IOException {
      InputStream in = new FileInputStream(src);
      OutputStream out = new FileOutputStream(dest);

      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0) {
         out.write(buf, 0, len);
      }

      in.close();
      out.close();
   }

   // Run application
   public static void main(String[] args) {
      if (args == null || args.length != 3 ) {
         System.out.println("Invalid program arguments");
         System.out.println("arg1 - a path to a data file");
         System.out.println("arg2 - a path to a directory that we are going to start our search");
         System.out.println("arg3 - file extension");
         System.out.println("example usage: java StringReplacerApp /home/user/projects/regex-data.txt /home/user/projects/my-project-directory xhtml");
        return;
      }

      String dataFilePath = args[0];
      String replaceDirectoryPath = args[1];
      fileExtension = args[2];

      try {
         // Load replace data
         loadReplaceData(dataFilePath);

         // Run directory processing
         File startingDirectory = new File(replaceDirectoryPath);
         if (startingDirectory.exists() && startingDirectory.isDirectory())
            processDirectory(startingDirectory);

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

Reading program arguments

   // Run application
   public static void main(String[] args) {
      if (args == null || args.length != 3 ) {
         System.out.println("Invalid program arguments");
         System.out.println("arg1 - a path to a data file");
         System.out.println("arg2 - a path to a directory that we are going to start our search");
         System.out.println("arg3 - file extension");
         System.out.println("example usage: java StringReplacerApp /home/user/projects/regex-data.txt /home/user/projects/my-project-directory xhtml");
        return;
      }

      String dataFilePath = args[0];
      String replaceDirectoryPath = args[1];
      fileExtension = args[2];
      ...

Program parameters are held in an args array containing String objects variable which is passed to the main method of the application.

Reading and writing files in java

   // Process file
   private static void processFile(File file) throws IOException {
      System.out.println("Processing file " + file.getName());
      // If a file has an appropriate extension then process it
      if (file.getName().indexOf(fileExtension) != -1) {
         // Reading objects
         FileInputStream fis = new FileInputStream(file);
         DataInputStream in = new DataInputStream(fis);
         BufferedReader br = new BufferedReader(new InputStreamReader(in));

         // Writing objects
         File tmpFile = new File(file.getAbsolutePath() + "_tmp");
         FileWriter fw = new FileWriter(tmpFile);
         BufferedWriter out = new BufferedWriter(fw);

         String line;
         while ((line = br.readLine()) != null) {
            for (String replaceKey: replaceStrings.keySet()) {
               if (line.indexOf(replaceKey) != -1)
                  line = line.replaceAll(replaceKey, replaceStrings.get(replaceKey));
            }
            out.write(line+"\n");
         }

         br.close();
         in.close();
         fis.close();

         out.close();
         fw.close();
         ...

File data is being read and written in a form of String objects that represents whole lines.

Coping file bytes from one to another in java

   // Copy from file to file.
   private static void copyFile(File src, File dest) throws IOException {
      InputStream in = new FileInputStream(src);
      OutputStream out = new FileOutputStream(dest);

      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0) {
         out.write(buf, 0, len);
      }

      in.close();
      out.close();
   }

This code is responsible for raw file data.

Recursive file and directories processing in java

   // Process directory
   private static void processDirectory(File directory) throws IOException {
      System.out.println("Processing directory " + directory.getName());

      for (File node: directory.listFiles()) {
         if (node.isFile())
            processFile(node);
         else if (node.isDirectory())
            processDirectory(node);
      }
   }

This is an example code which checks if currently processed file system node is a file or directory. If node is a file it’s being processed and for directory nodes processDirectory method is called recursively.

Using Map interface in java

   // Load replace strings data.
   private static void loadReplaceData(String dataFile) throws IOException {
      System.out.println("Loading replace data from file " + dataFile);

      replaceStrings = new HashMap<String, String>();

      FileInputStream fstream = new FileInputStream(dataFile);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      String line;
      while ((line = br.readLine()) != null) {
         String[] lineSplit = line.split(SEPARATOR);
         System.out.println("reading replace: " + lineSplit[0] + " with:" + lineSplit[1]);
         replaceStrings.put(lineSplit[0], lineSplit[1]);
      }

      br.close();
      in.close();
      fstream.close();
   }

This method is parsing a file which contains replace strings definitions. Each definition is a line in a following form


a string to replace===>a string to replace with
a string to replace===>a string to replace with
a string to replace===>a string to replace with
a string to replace===>a string to replace with

During this file processing a replaceStrings map is constructed where key is a string which we want to replace and a value is a string that we want to replace our string with.

         String line;
         while ((line = br.readLine()) != null) {
            for (String replaceKey: replaceStrings.keySet()) {
               if (line.indexOf(replaceKey) != -1)
                  line = line.replaceAll(replaceKey, replaceStrings.get(replaceKey));
            }
            out.write(line+"\n");
         }

This replaceStrings map is used during file searching process. We check every file line against map key set to find out if that line contains a string that we want to replace.

That’s about it. This application speed can be improved by implementing multi thread directory processing which we are going to show You in another post.

If You feel like asking about something don’t hesitate and do it in the comment space below. We are here to answer.

Application source code in a form of Eclipse project is available here.

5 Responses to "How to write string replace java application"

  1. Praveen Kumar says:

    sir
    can we define any method with any name in a class with one String array argument?????

    if yes then send me code of this programme and not then why its is not

    Reply
  2. Shruthi says:

    Hello there, This code does not really work for me. Here’s how I teestd it. My test.txt file is saved with UTF-8 encoding and contains this line: w e9te9 jedn? stron? f4pe8e7 dbg fcte0 My test program below first reads the file in BufferedReader and then writes in Writer. package test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer;public class Test_temp { public Test_temp() { String sPath = E:/workspace/project/src/test/test.txt ; if (sPath != null && !sPath.trim().equals( )) { try { Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(sPath + .new ), UTF8 )); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sPath), UTF8 )); String s = null; while ((s = in.readLine()) != null) { String UTF8Str = new String(s.getBytes(), UTF8 ); System.out.println( [" + UTF8Str + "] ); out.append(UTF8Str).append( \r\n ); } System.out.println( Reading Process Completly Successfully. ); in.close(); out.flush(); out.close(); } catch (UnsupportedEncodingException ue) { System.out.println( Not supported : + ue.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } } } public static void main(String[] args) { new Test_temp(); } } The new generated file (test.txt.new) is also encoded with UTF-8 but characters are corrupted: ?w ?t? jedn? stron? ?p?? ?g ? Could you please tell me what do I do wrong? Thanks

    Reply
    • itcuties says:

      Hi. We have tested this code and replaced line

      String UTF8Str = new String(s.getBytes(),"UTF8");

      with

      String UTF8Str = new String(s.getBytes());

      You don’t need to double code your string with UTF8 :)
      It works well with our polish signs.

      Cheers,
      itcuties

      Reply
  3. tyce says:

    String UTF8Str = new String(s.getBytes());

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>