码迷,mamicode.com
首页 > 其他好文 > 详细

修改文件内容

时间:2019-12-30 19:02:02      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:get   string   equals   trace   upd   stack   append   adl   catch   

/***
     *  
     * @param path 文件地址  文件默认存贮 
     * @param key  通过key找到要修改的对应行的value
     * @param newValue  替换值
     */
    public static void replaceTxt(String path,String key,String newValue) {
        String temp = "";
        try {
            //读取文件
            File file = new File(path);
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            //文件内容临时保存
            StringBuffer buf = new StringBuffer();
            // 保存该行前面的内容
            while ( (temp = br.readLine()) != null) {
                //判断是否是要修改的对应行
                boolean isUpdata=temp.equals(key);
                if(isUpdata){ //修改对应行的值
                    buf = buf.append(newValue);
                }else{//保存不用修改的值
                    buf = buf.append(temp);
                }
                //添加换行
                buf = buf.append(System.getProperty("line.separator"));
            }
            //关闭读流
            br.close();
            //并将文件重新写入
            FileOutputStream fos = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

修改文件内容

标签:get   string   equals   trace   upd   stack   append   adl   catch   

原文地址:https://www.cnblogs.com/why5125/p/12120987.html

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