update a file in java
to update a file first we have to read from file and then update the contents of that file.
import java.io.*; public class UpdateFile { public static void main(String[] args) throws Exception { File f = new File("c:/new.txt"); // check if file exists or not boolean exists = f.exists(); StringBuffer buffer = new StringBuffer(); String str; BufferedReader br = new BufferedReader(new FileReader(f)); while (true) { str = br.readLine(); if (str == null) break; buffer.append(str); } String st1 = "All"; int c1 = buffer.indexOf(st1); buffer.replace(c1, c1 + st1.length(), "Some"); String st2 = "not gold"; int c2 = buffer.indexOf(st2); buffer.replace(c2, c2 + st2.length(), "Diamond"); br.close(); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.write(buffer.toString()); bw.close(); } }