如何在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