個人博客 地址:http://www.wenhaofan.com/article/20180913160442
代碼如下
package com.wenhaofan.common.kit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import com.jfinal.kit.PropKit;
/**
* @author 作者:范文皓
* @createDate 創建時間:2018年9月13日 下午3:59:07
*/
public class PropertyKit {
public static void main(String[] args) {
String path=FileKit.class.getResource("/blog_config.txt").getPath() ;
path=path.substring(1, path.length());
replace(path,"theme","newTheme");
String theme=PropKit.use("blog_config.txt").get("theme");
System.out.println(theme);
}
public static void replace(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 isMath=StrKit.filterNull(temp).split("=")[0].equals(key);
if(isMath){
buf = buf.append(key+"="+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();
}
}
}
實現思路
按行讀取指定文本中的內容,將內容添加進StringBuffer中,
如果當前行號為指定行號則添加替換的內容,否則添加原內容
然后將StringBuffer中的內容覆蓋寫入文件
