If we pass a file path and a word and the replace word to a method then it will replace all the word in that file with replace word.
/************************
* Code to replace all word in a test file
************************/
import java.io.*;
public class repalceWord {
/*Repalces words in a file*/
public static void contentReplace(String filepath,String word,String replaceword) {
//String filepath="D:/test.txt";
//String word="something";
//String replaceword="evertthing";
String data="";
File file=new File(filepath);
try{
FileInputStream fis = new FileInputStream(file);/*creates a new file input stream */
InputStreamReader is = new InputStreamReader(fis);/*Creates a new file input stream*/
BufferedReader br = new BufferedReader(is);/*creates a buffer reader*/
String strLine="";
while ((strLine = br.readLine()) != null)/*checks if their are any lines in a file
{
if(strLine.contains(word)){ /*checks if the file contains such a word*/
data+=strLine.replaceAll(word, replaceword)+"n";/*It replaces all the words in the file*/
}else{
data+=strLine+"n";/*If no such word it moves to next line*/
}
}
System.out.println(data);
br.close();
is.close();
fis.close();
FileOutputStream fileOutputStream=new FileOutputStream(filepath,false);/*creates a new file output stream */
Writer outx=new OutputStreamWriter(fileOutputStream);/*creates a Writer for the file output stream */
if(data.contains("n")){
String[] list=data.split("n");/*split the data*/
for(int i=0;i<list.length;i++){
outx.write(list[i]);
outx.append("n");
}
}else{
outx.write(data);
outx.append("n");
}
outx.close();
fileOutputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}