Posted By

nialace on 12/03/10


Tagged

file


Versions (?)

Replace a line or word in a file


 / Published in: Java
 

URL: http://www.java.happycodings.com/Core_Java/code69.html

file.txt I drink Java I sleep Java This is test string 1 This is test string 20000

  1. import java.io.*;
  2.  
  3. public class BTest
  4. {
  5. public static void main(String args[])
  6. {
  7. try
  8. {
  9. File file = new File("file.txt");
  10. BufferedReader reader = new BufferedReader(new FileReader(file));
  11. String line = "", oldtext = "";
  12. while((line = reader.readLine()) != null)
  13. {
  14. oldtext += line + "
  15. ";
  16. }
  17. reader.close();
  18. // replace a word in a file
  19. //String newtext = oldtext.replaceAll("drink", "Love");
  20.  
  21. //To replace a line in a file
  22. String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
  23.  
  24. FileWriter writer = new FileWriter("file.txt");
  25. writer.write(newtext);writer.close();
  26. }
  27. catch (IOException ioe)
  28. {
  29. ioe.printStackTrace();
  30. }
  31. }
  32. }

Report this snippet  

You need to login to post a comment.