码迷,mamicode.com
首页 > 编程语言 > 详细

java修改文件内容

时间:2017-09-03 00:18:19      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:exception   lin   mac   地方   rand   tac   pat   stp   stat   

       文件的读和写,大家都不陌生,但是修改呢?按照普通的读写流去修改的话,只能全部读取出来,在内存中修改好后,全部写进去,这样对于文件内容过多的时,性能很低。

最近在遇到这个问题的时候,发现RandomAccessFile这个类正好能解决我的问题,废话不多说,下面直接贴代码,分享给大家,有不对的地方欢迎指教,谢谢

 

    /**
     * 修改文件内容
     * @param fileName
     * @param oldstr
     * @param newStr
     * @return
     */
    private static boolean modifyFileContent(String fileName, String oldstr, String newStr) {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(FILEPATH+"/"+fileName, "rw");
            String line = null;
            long lastPoint = 0; //记住上一次的偏移量
            while ((line = raf.readLine()) != null) {
                final long ponit = raf.getFilePointer();
                if(line.contains(oldstr)){
                      String str=line.replace(oldstr, newStr);
                raf.seek(lastPoint);
                raf.writeBytes(str);
                }
                lastPoint = ponit;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

 

java修改文件内容

标签:exception   lin   mac   地方   rand   tac   pat   stp   stat   

原文地址:http://www.cnblogs.com/XiaoyangBoke/p/7468268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!