INI(Initialization)文件是一种常见的配置文件格式,通常用于存储应用程序的配置信息。INI文件通常包含一系列的节(sections)和键-值对(key-value pairs)。每个节包含一组相关的键-值对。
; 这是注释 [Database] Server = localhost Port = 3306 Username = myuser Password = mypassword
以下是java对INI文件的读写操作
package file.ini; import java.io.*; import java.util.HashMap; import java.util.Map; public class INIFIleReader { private Map<String, Map<String,String>> sections = new HashMap<>(); public void readINIFile(String path){ BufferedReader reader = null; try{ reader = new BufferedReader(new FileReader(path)); String line; String currentSection = null; while((line = reader.readLine()) != null){ line = line.trim(); //忽略#;空开头的空行、注释 if(line.isEmpty() || line.startsWith(";") || line.startsWith("#")){ continue; } if (line.startsWith("[")){ //解析节 int endIndex = line.indexOf("]"); if(endIndex > 0){ currentSection = line.substring(1,endIndex); sections.put(currentSection,new HashMap<>()); } }else { //解析属性 int separatorIndex = line.indexOf("="); if(separatorIndex > 0 && currentSection !=null){ String key = line.substring(0,separatorIndex).trim(); String value = line.substring(separatorIndex + 1).trim(); sections.get(currentSection).put(key,value); } } } }catch (IOException e){ try {//读写失败则新建一个ini文件 FileWriter fileWriter = new FileWriter("config.ini"); PrintWriter printWriter = new PrintWriter("config.ini"); printWriter.println("[Section1]"); printWriter.println("key1=value1"); printWriter.println("key2=value2"); printWriter.close(); }catch (IOException e1){ e1.printStackTrace(); } e.printStackTrace(); } finally { if (reader !=null){ try{ reader.close(); }catch (IOException e){ e.printStackTrace(); } } } } public String getProperty(String section,String key){ Map<String, String> properties = sections.get(section); if (properties !=null) { return properties.get(key); } return null; } //遍历Map数组 public void ForEach(){ sections.forEach((key,value) -> System.out.println(key + "=" +value)); } public static void main(String[] args){ INIFIleReader reader = new INIFIleReader(); reader.readINIFile("config.ini"); String value = reader.getProperty("Section1","key1"); System.out.println(value); reader.ForEach(); } }
标签:String,读写,value,ini,key,reader,new,line,20231106 From: https://www.cnblogs.com/xxaxf/p/17813908.html