Program to Replace all the occurrences of searchWord in the file with replaceWord in java using byte array

Let’s say c:/myFile.txt looks like this >
abc is the string abc this is abc

1) Read file in String (i.e. in fileDataInString).
2) Replace all the occurrences of searchWord in the file (i.e. in fileDataInString) with replaceWord by using replaceAll method of String.
3) Now, write fileDataInString in file.



Program to Replace all the occurrences of searchWord in the file with replaceWord in java >

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ReplaceAllOccurrencesOfStringInFileUsingByteArray {
   public static void main(String[] args) {
         
          String fileName ="c:/myFile.txt";
          String searchWord= "abc";
          String replaceWord= "xyz";
         
         
          try {
                 //1) Read file in String (i.e. in fileDataInString).
                 FileInputStream fis = new FileInputStream(fileName);
                 byte b[] = new byte[fis.available()]; //use byte Array
                 fis.read(b);
                 String fileDataInString = new String(b);
                 fis.close();
                 //By now, String fileDataInString contains all the data of file.
                
                
                 //2) Replace all the occurrences of searchWord in the file (i.e.
                 //in fileDataInString) with replaceWord by using replaceAll method of String
                 fileDataInString = fileDataInString.replaceAll(searchWord, replaceWord);
                
                 //3) Now, write fileDataInString in file
                 FileOutputStream fos = new FileOutputStream(fileName, false);
                 fos.write(fileDataInString.getBytes());
                 fos.close();
                
                 System.out.println("all occurrences of "+searchWord+" has been replaced with "
                              +replaceWord+" in "+fileName);
          } catch (FileNotFoundException e) {
                 e.printStackTrace();
          } catch (IOException e) {
                 e.printStackTrace();
          }
         
   }
}
/*OUTPUT
all occurrences of abc has been replaced with xyz in c:/myFile.txt
*/



After executing above program all occurrences of abc will be replaced with xyz, and c:/myFile.txt will look like this >
xyz is the string xyz this is xyz




RELATED LINKS>

Create File using createNewFile() method in java file IO


Copy a file in java 2 in ways


Read text from file using FileInputStream in java file IO


Read text from file using BufferedInputStream (and FileInputStream) in java file IO


Find current directory or current path in java


eEdit
Must read for you :