Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để xóa một chuỗi bên trong tệp (.txt) trong java?

ReplaceAll () phương thức chấp nhận một biểu thức chính quy và một Chuỗi làm tham số và khớp nội dung của chuỗi hiện tại với biểu thức chính quy đã cho, trong trường hợp khớp, sẽ thay thế các phần tử đã khớp bằng Chuỗi.

Để xóa một chuỗi cụ thể khỏi tệp bằng phương thức ReplaceAll () -

  • Truy xuất nội dung của tệp dưới dạng chuỗi.

  • Thay thế từ bắt buộc bằng một Chuỗi trống bằng phương thức ReplaceAll ().

  • Viết lại chuỗi kết quả vào tệp một lần nữa.

Ví dụ

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));
   }
}

Đầu ra

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