How to delete a string inside a file(.txt) in java?

The replaceAll() method accepts a regular expression and a String as parameters and, matches the contents of the current string with the given regular expression, in case of match, replaces the matched elements with the String.

To delete a particular String from a file using the replaceAll() method −

  • Retrieve the contents of the file as a String.

  • Replace the required word with an empty String using the replaceAll() method.

  • Rewrite the resultant string into the file again.


import java.util.Scanner;
public class StringExample {
   public static String fileToString(String filePath) throws Exception{
      String input = null;
      Scanner sc = new Scanner(new File(filePath));
      StringBuffer sb = new StringBuffer();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
      return sb.toString();
   public static void main(String args[]) throws FileNotFoundException {
      String filePath = "D://sample.txt";
      String result = fileToString(filePath);
      System.out.println("Contents of the file: "+result);
      //Replacing the word with desired one
      result = result.replaceAll("\bTutorialspoint\b", "");
      //Rewriting the contents of the file
      PrintWriter writer = new PrintWriter(new File(filePath));
      System.out.println("Contents of the file after replacing the desired word:");


Contents of the file: Hello how are you welcome to Tutorialspoint
Contents of the file after replacing the desired word:
Hello how are you welcome to