修改 yml,properties,ini 格式文件
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.*;
public class UpdateYml {
public static void update(File file,String readerStoreDir){
Yaml yml =null;
Map<String,Object> obj =null;
try (FileInputStream in = new FileInputStream(file)){
yml = new Yaml();
obj = (Map)yml.load(in);
} catch (IOException e) {
e.printStackTrace();
}
HashMap<String,Object> reader = (HashMap<String, Object>) obj.get("reader");
HashMap<String,Object> store = (HashMap<String, Object>) reader.get("store");
Object dir = store.get("dir");
String s = String.valueOf(dir);
store.put("dir", readerStoreDir);
try (FileWriter writer = new FileWriter(file)) {
writer.write(yml.dumpAsMap(obj));
} catch (IOException e) {
e.printStackTrace();
System.out.println("修改yml文件出错了");
}
}
public static void updatePropertiesJdbc(String propertiesPath){
OutputStream fos=null;
try {
Properties props=new Properties();
props.load(new FileInputStream(propertiesPath));
props.setProperty("jdbc.url", "jdbc:mysql://127.0.0.1:3306/doc_standards?characterEncoding=UTF-8");
props.setProperty("jdbc.username", "root");
props.setProperty("jdbc.password", "123456");
fos =new FileOutputStream(propertiesPath);
props.store(fos, "修改jdbc");
fos.close();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
fos.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
public static void updateConfigFile(String configPath, Map<String, String> map) {
Map<String, String> listMap = getListMap(new File(configPath));
for (Map.Entry<String, String> entry : map.entrySet()) {
listMap.put(entry.getKey(),entry.getValue());
}
File file=new File(configPath);
try (
OutputStream out=new FileOutputStream(file,false);
OutputStreamWriter osw=new OutputStreamWriter(out,"utf-8");
BufferedWriter bw=new BufferedWriter(osw);
){
for (Map.Entry<String, String> entry : listMap.entrySet()) {
bw.write(entry.getKey()+"="+entry.getValue());
bw.newLine();
}
bw.flush();
}catch (Exception e){
e.printStackTrace();
}
}
private static Map<String,String> getListMap(File file){
Map<String,String> map=new LinkedHashMap<>();
List<String> stringList=new ArrayList<>();
try(InputStream in=new FileInputStream(file);
InputStreamReader inr=new InputStreamReader(in,"utf-8");
BufferedReader br=new BufferedReader(inr);
){
String str;
while ((str=br.readLine())!=null){
stringList.add(str);
}
}catch (Exception e){
e.printStackTrace();
}
for (String line : stringList) {
if(line.startsWith("#")) {
continue;
}
if(isWhiteSpace(line)) {
continue;
}
if(!line.contains("=")){
continue;
}
int fd = line.indexOf("=");
String key = line.substring(0, fd);
String value = line.substring(fd + 1);
map.put(key,value);
}
return map;
}
private static boolean isWhiteSpace(String line) {
return line.replace(" ", "").equals("");
}
}