java实现对txt文件读入,替换部分文字后写出到另一个文件

package com;
import java.io.*;

public class test {

public static void Test(String oldfilePath,String newfilePath){
    File file = new File(oldfilePath);
    //判断文件存在并且是文件
    Boolean boo = file.exists()&&file.isFile();
    System.out.println(boo);
    if (boo) {
        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) {
                System.out.println(linetxt);
                String newconttent = linetxt.replace("china","中国");//替换
                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();
            }
        }
    }else{
        System.out.println("找不到指定的文件");
    }
}



public static void main(String argv[]){
    String oldfilePath = "E:\\毕业设计图\\test\\data\\content.txt";//content.txt路径。记得改

    String newfilePath = "E:\\毕业设计图\\test\\data\\aim.txt";//aim.txt路径,记得改
    Test(oldfilePath,newfilePath);
}

}

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值