如何在Java中删除文件(.txt)中的字符串?
replaceAll()方法接受一个正则表达式和字符串作为参数,并且在当前字符串与给定正则表达式匹配的内容,在匹配的情况下,替换字符串匹配的元素。
使用replaceAll()方法从文件中删除特定的字符串-
以字符串形式检索文件的内容。
使用方法将所需的单词替换为空的StringreplaceAll()。
再次将结果字符串重写到文件中。
示例
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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短