首页 > 其他 > 详细

修改文件内容

时间:2019-12-30 19:01:43      阅读:81      评论:0      收藏:0      [点我收藏+]
/***
     *  
     * @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();
        }
    }

修改文件内容

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!