首页 > 编程语言 > 详细

java修改文件内容

时间:2019-05-02 23:25:57      阅读:106      评论:0      收藏:0      [点我收藏+]

项目使用到了需要将配置文件中指定内容替换为想要更新的内容,特此记下,已被后用

/**
	 * 
	 * @param fileName 要修改的文件名
	 * @param oldstr 要修改的字段
	 * @param newStr 替换的字段
	 */
	public static Boolean updateStartBat(String fileName, String oldstr, String newStr){
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(PathUtil.appPath +File.separator +"nginx-1.14.2"
					+ File.separator + File.separator+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 (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		} finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return true;
	}

  

java修改文件内容

原文:https://www.cnblogs.com/wangjinyu/p/10803596.html

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