Friday, 15 August 2014

I want to open a text file and edit a specific line in java -


This is a code written instead of editing a particular line. I ....

  PrintWriter author = new print-वाटर (new buffet वाटर (new flamerer ("D: \\ book.txt", true))); Buffettarder BRL = Faucet; FileReader Reader = Faucet; Try {Reader = new FileReader ("d: \\ book.txt"); Br = new buffated reader (reader); String line; System.out.println ((";;;;;;;;;;;;;;;;;;;;; 0; ll .getparameter (" hname ")); Println (request.getParameter ( "Book"); while ((line = breadline ())! = Null () (if (request.getParameter ("hname"). Par (line)) {line = line.replace (request.getParameter ("hname" "GetParameter" ("book"); writer.println (line); writer.close ();}}} hold (FileNotFoundException e) {e.printStackTrace ();} Finally {reader.close () ;}    

Unless you are changing the length (byte) of the line, Then you should rewrite the whole file, where the changed line must be added. It's just a simple change from the current code. First, start your FileWriter without app (because you do not ) just append it to the end of the file

  Print-Author Writer = New Print-Authors (New Buffed Vector (New Flemer ("D: \\ book.txt") After that, read the whole file in memory (if the file is too small) or you write a temporary file as you go And then copy it if you work. The second method is more robust, and requires less code replacement; Just modify the loop of your time so that every line can be modified or not. Open a temporary file to write  
  //. Printwriter author = new print-viter (new buffed viter (new flamer ("D: \\ book.temp"))); // ... then inside your loop ... while ((line = br.readline ()) = null {} (request.getParameter ("hname"). Par (line)) {line = line.replace (Request.getParameter ("hname"), request.getParameter ("book")); } // Always write the line, whether you have changed it or not author.println (line); } // ... and finally ... file real name = new file ("d: \\ book.txt"); RealName.delete (); // Delete the old file new file ("D: \\ book.temp") .name (real name); // Rename Temporary File   

Do not forget to close all your files when you do!

No comments:

Post a Comment