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.

Example

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
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();
         sb.append(input);
      }
      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));
      writer.append(result);
      writer.flush();
      System.out.println("Contents of the file after replacing the desired word:");
      System.out.println(fileToString(filePath));
   }
}

Output

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
raja
Published on 10-Oct-2019 12:42:30
Advertisements