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

java修改文件内容

时间:2019-05-02 23:37:54      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:nal   news   nginx   class   byte   point   read   ppp   try   

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

/**
	 * 
	 * @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修改文件内容

标签:nal   news   nginx   class   byte   point   read   ppp   try   

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

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