How to replace specific string in text file in java?
We are defining one method called modifyFile(). This method reads all the content of input text file into a String object, replaces the old string with new string and rewrites the new content back into the same file. It takes three arguments : Path of the file to be modified – filepath, string to be replaced – oldString and string to be replaced with – newString. Let’s see how this method works step by step.
Step 1 : Create a File object by passing the path of the file to be modified.
File fileToBeModified = new File(filePath)
Step 2 : Initialize oldContent with an empty string. This String object will hold all the old content of the input text file.
String oldContent = “”
Step 3 : Create BufferedReader object to read the input text file line by line.
BufferedReader reader = new BufferedReader(new FileReader(fileToBeModified))
Step 4 : Read all the lines of input text file one by one and append it to oldContent.
String line = reader.readLine();
while (line != null)
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
Step 5 : Replace all the occurrences of oldString with newString using replaceAll() method. You will get a newContent.
String newContent = oldContent.replaceAll(oldString, newString)
Step 6 : Now create FileWriter object to write newContent back into the input text file fileToBeModified.
FileWriter writer = new FileWriter(fileToBeModified)
Step 7 : Rewrite the fileToBeModified with newContent using write() method of FileWriter object.
Step 8 : Close the resources.