如何在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 婆婆高寿祝福语大全简短