replaceAll() เมธอดยอมรับนิพจน์ทั่วไปและสตริงเป็นพารามิเตอร์ และจับคู่เนื้อหาของสตริงปัจจุบันกับนิพจน์ทั่วไปที่กำหนด ในกรณีที่ตรงกัน จะแทนที่องค์ประกอบที่ตรงกันด้วยสตริง
หากต้องการลบสตริงเฉพาะออกจากไฟล์โดยใช้เมธอด replaceAll() -
-
ดึงเนื้อหาของไฟล์เป็นสตริง
-
แทนที่คำที่ต้องการด้วยสตริงว่างโดยใช้เมธอด replaceAll()
-
เขียนสตริงผลลัพธ์ลงในไฟล์อีกครั้ง
ตัวอย่าง
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));
}
} ผลลัพธ์
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