Java替换文件夹中txt某一个字符

该代码示例展示了如何使用Java遍历指定文件夹中的所有TXT文件,并将文件中的某个字符(如“普通用户”)替换为另一个字符(如user)。通过BufferedReader和PrintStream实现文件内容读取、替换及写回操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java替换文件夹中txt某一个字符

替换文件夹中txt某一个字符

 public void testTH(){
        String filePath = "F:\\代码\\extract-data\\storage-cassandra\\data";
        String path = "F:\\代码\\extract-data\\storage-cassandra\\datax";

        File fileDir = new File(filePath);
        //遍历文件
        for (File file : fileDir.listFiles()) {
            String newFileName = file.getName();
            String newfilePath = path + File.separator + newFileName;
            BufferedReader bufferedReader = null;
            try {
                //构造一个BufferedReader类来读取文件
                bufferedReader = new BufferedReader(new FileReader(file));
                String linetxt = null;
                //result用来存储文件内容
                StringBuilder result = new StringBuilder();
                //按使用readLine方法,一次读一行
                while ((linetxt = bufferedReader.readLine()) != null) {
               /* String newconttent = linetxt.replace("|","");//替换
                result.append(newconttent);*/
                    String newconttent = linetxt.replace("普通用户","user");//替换
                    result.append(newconttent);
                    File newfile = new File(newfilePath);
                    PrintStream ps = new PrintStream(new FileOutputStream(newfile, true));
                    ps.println(newconttent);// 往aim.txt文件里写入字符串
                }
                //输出读出的所有数据(StringBuilder类型)
//            System.out.println(result);
                //对文件内容操作


            } catch (Exception e) {
                System.out.println("读取文件内容出错");
                e.printStackTrace();
            }finally {
                try {
                    bufferedReader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值