如何在Java中刪除檔案中(.txt)的字串?
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP