replaceAll()方法接受一个正则表达式和字符串作为参数,并且在当前字符串与给定正则表达式匹配的内容,在匹配的情况下,替换字符串匹配的元素。
使用replaceAll()方法从文件中删除特定的字符串-以字符串形式检索文件的内容。
使用方法将所需的单词替换为空的String 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);
//用所需的单词替换单词
result = result.replaceAll("\\bNhooo\\b", "");
//重写文件内容
PrintWriter writer = new PrintWriter(new File(filePath));
writer.append(result);
writer.flush();
System.out.println("替换所需单词后的文件内容:");
System.out.println(fileToString(filePath));
}
}
输出结果Contents of the file: Hello how are you welcome to Nhooo
替换所需单词后的文件内容:
Hello how are you welcome to