博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Java】Txt 文件内容替换
阅读量:4610 次
发布时间:2019-06-09

本文共 1524 字,大约阅读时间需要 5 分钟。

//将str1替换为str1    //FilePath为文件路径    public void changeTxtContent(String FilePath,String str1,String str2) throws Exception{        File file = new File(FilePath);        String code = getFileCharacterEnding(file);//获取文件编码        InputStreamReader read = new InputStreamReader(new FileInputStream(            file), code);        BufferedReader bufferedReader = new BufferedReader(read);        String TxtBuff=null;        String out="";        while((TxtBuff = bufferedReader.readLine()) !=null){            TxtBuff = TxtBuff.replace(str1, str2);            out+= TxtBuff;        }        read.close();        FileOutputStream outputstream=null;         outputstream = new FileOutputStream(file);        outputstream.write(out.getBytes(code));          outputstream.close();     }

获取文件编码

public static String getFileCharacterEnding(File file) throws Exception {        InputStream inputStream = new FileInputStream(file);         byte[] head = new byte[3];          inputStream.read(head);           String code = "gbk";        if (head[0] == -1 && head[1] == -2){            code = "UTF-16";        }        if (head[0] == -2 && head[1] == -1){            code = "Unicode";        }        if (head[0] == -17 && head[1] == -69 && head[2] == -65){            code = "UTF-8";        }        try{ inputStream.close();}catch (Exception e) {}        System.out.println(code);                 return code;    }

 

这种方法应该不适合跨行内容的替换,如果要换行内容要替换的话 ,可以试下 out=out.replace(str1, str2);

转载于:https://www.cnblogs.com/4evercai/p/3490181.html

你可能感兴趣的文章
牛人们的博客地址
查看>>
Zabbix是什么?
查看>>
Dede推荐文章与热点文章不显示?
查看>>
Linux --Apache服务搭建
查看>>
20145325张梓靖 实验三 "敏捷开发与XP实践"
查看>>
JavaScript面试题
查看>>
[转帖]架构师眼中的高并发架构
查看>>
ios的一些开源资源
查看>>
HTTP 错误 500.21 - Internal Server Error 解决方案
查看>>
Bucks sign Sanders to $44 million extension
查看>>
【PHP】Windows下配置用mail()发送邮件
查看>>
Nhibernate和EF的区别
查看>>
基于java spring框架开发部标1078视频监控平台精华文章索引
查看>>
人类简史
查看>>
java 设计模式学习
查看>>
【Python使用】使用pip安装卸载Python包(含离线安装Python包)未完成???
查看>>
一语道破项目管理知识体系五大过程组
查看>>
C# 备份、还原、拷贝远程文件夹
查看>>
在windows环境下运行compass文件出现的错误提示解决方案
查看>>
CSS常用样式--font
查看>>