Ishmam_Rahman

Replace file text and delete file in Java

May 6th, 2021
631
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.io.File;
  2. import java.io.IOException;
  3.  
  4. import org.apache.commons.io.FileUtils;
  5.  
  6. public class Example {
  7.     public static void main(String[] args) {
  8.         File textFile = new File("Myself.txt");
  9.         try {
  10.             String data = FileUtils.readFileToString(textFile);
  11.             data = data.replace("Khadija", "Saiyana");
  12.             FileUtils.writeStringToFile(textFile, data);
  13.         } catch (IOException e) {
  14.             e.printStackTrace();
  15.         }
  16.        
  17.         File myObj = new File("Myself.txt");
  18.         if (myObj.delete()) {
  19.             System.out.println("Deleted the file: " + myObj.getName());
  20.         } else {
  21.             System.out.println("Failed to delete the file.");
  22.         }
  23.     }
  24. }
RAW Paste Data