Read a File and Replace a String from a JAVA Program

This Java sample program shows illustrates two things. 1. How to replace a string with another string. 2. How to read from a file and write to a File from Java.

This program was needed in one of my projects where I get a text file A which is updated every two minutes by another program. I had to read this file and replace the occurrence of a particular String in that file with another String. However I cannot edit the file A since it was shared by other programs. Therefore after I replaced the String I created my own file B for my further processing. This free sample program does just that.

/*
 *
 * A free Java sample program 
 * to read a file A and replace occurrence of a String
 * with another String and write the result to another file B
 *
 * free for use as long as this comment is included 
 * in the program as it is
 * 
 * More Free Java programs available for download 
 * at http://www.java-samples.com
 *
 */

import java.net.*;
import java.io.*;
import java.util.*;
public class replace
{
    public static void main(String args[]) throws Exception
    {
       
	   if (args.length != 4)
           {
		System.err.println ("Invalid command parameters");
		System.exit(0);
           }

String str;	
try{
FileInputStream	fis2=new FileInputStream(args[2]);
DataInputStream   input = new DataInputStream (fis2);
FileOutputStream fos2=new FileOutputStream(args[3]);
DataOutputStream   output = new DataOutputStream (fos2);

while (null != ((str = input.readLine())))
{



String s2=args[0];
String s3=args[1];

int x=0;
int y=0;
String result="";
while ((x=str.indexOf(s2, y))>-1) {
  result+=str.substring(y,x);
  result+=s3;
  y=x+s2.length();
 }
result+=str.substring(y);
str=result;

if(str.indexOf("'',") != -1){
	continue;
}
else{
str=str+"\n";

output.writeBytes(str);
}
        }
       }
        catch (IOException ioe)
        {
            System.err.println ("I/O Error - " + ioe);
        }
    }
}

More Free Java Sample Code