Search and Replace Content inside a File
Today, We are going to see how to search a file for specific content and replace the content and write to a new File.
Let us create a text document with some content in it
Now we are going to write a code to change “File 1” into “File 2”, The content will be
“Sample Content in File 2”
public class FileOperation { public static void main(String[] args) throws Exception { try { File file = new File("F://File1.txt"); BufferedReader reader = new BufferedReader(new FileReader(file)); String line = "", oldtext = ""; while((line = reader.readLine()) != null) { oldtext += line + "\r\n"; } reader.close(); String replacedtext = oldtext.replaceAll("File 1", "File 2"); FileWriter writer = new FileWriter("F://File2.txt"); writer.write(replacedtext); writer.close(); } catch (IOException ex ) { ex.printStackTrace(); } } }
Once the code is executed, File2.txt will get created and content will be,