项目使用到了需要将配置文件中指定内容替换为想要更新的内容,特此记下,已被后用
/**
*
* @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;
}