java删除文件中的字符串_如何在Java中删除文件(.txt)中的字符串?

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值