If you do not change the byte length of the line, you need to rewrite the entire file, adding, if necessary, the modified line. This is actually just a simple change to your current code. Initialize FileWriter first without append (since you donβt want to just add to the end of the file what you are doing now).
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.txt")));
Then either read the entire file in memory (if the file is small enough), or write a temporary file as it arrives, and then copy it when you're done. The second method is more reliable and requires less code change; just modify the while loop to write each line, modified or not.
// Open a temporary file to write to. PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.temp"))); // ... then inside your loop ... while ((line = br.readLine()) != null) { if (request.getParameter("hname").equals(line)) { line = line.replace(request.getParameter("hname"), request.getParameter("book")); } // Always write the line, whether you changed it or not. writer.println(line); } // ... and finally ... File realName = new File("d:\\book.txt"); realName.delete(); // remove the old file new File("d:\\book.temp").renameTo(realName); // Rename temp file
Remember to close all your files when done!
source share