當我們要讀取或寫入INI config file的時候,可以透過apache commons的HierarchicalINIConfiguration來處理,如此可以針對每個section來讀取key及value,還可以建立新的section
#引用到的Library如下:
commons-configuration-1.10.jar
apache-commons-lang.jar
org-apache-commons-logging.jar
#config.ini內容如下:
[account1]
name = Ben
age = 30
[account2]
name = Jacky
age = 24
#程式碼如下:
import java.io.File;
import java.util.Iterator;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.HierarchicalINIConfiguration;
import org.apache.commons.configuration.SubnodeConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
public class INIFileReadWrite {
public static void main(String[] args) {
// TODO Auto-generated method stub
HierarchicalINIConfiguration iniconfig = new HierarchicalINIConfiguration();
try {
System.out.println("Case 1. Read from config.ini");
System.out.println("Case 1.1. Display each section's data");
iniconfig.load(new File("config.ini"));
for(String section : iniconfig.getSections()) {
SubnodeConfiguration subnode = iniconfig.getSection(section);
ConfigurationNode node = subnode.getRootNode();
System.out.println("[section]: "+node.getName());
listKeyValue(subnode);
}
System.out.println();
System.out.println("Case 1.2. Get property value direct by 'section.key'");
System.out.println("[proterty]: account1.name, [value]: "+iniconfig.getProperty("account1.name"));
System.out.println();
System.out.println("Case 2. Write and save as config_new.ini");
System.out.println("Case 2.1. New a section 'account3'");
HierarchicalConfiguration.Node node = new HierarchicalConfiguration.Node();
node.setName("account3");
SubnodeConfiguration subnode = new SubnodeConfiguration(iniconfig, node);
subnode.addProperty("name", "John");
subnode.addProperty("age", "18");
listKeyValue(subnode);
iniconfig.getRootNode().addChild(node);
iniconfig.save("config_new.ini");
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void listKeyValue(SubnodeConfiguration subnode) {
Iterator<String> keys = subnode.getKeys();
while(keys.hasNext()) {
String key = keys.next();
System.out.println("[key]: "+key+"\t[value]: "+subnode.getString(key));
}
}
}
#如何讀取section下的value?
一、輪詢section及key
首先宣告一HierarchicalINIConfiguration,並且載入config.ini後進行sections的輪詢取得
SubnodeConfiguration instance,此時getRootNode(其Class Type為HierarchicalConfiguration.Node,可以透過debug mode搭配breakpoint辨認到,見圖二),這個node指的就是section! 而section下的keys and values可以由subnode instance取得!
二、由root node呼叫getProperty
再來另一種取得value的方式,可以由iniconfig透過getProperty 並指定"section.key"的方式取得
#如何建立section及key、value?
參考read時相關的instance class type,反推回來發現要建立section首先需要new一個HierarchicalConfiguration.Node,再來是new一SubnodeConfiguration需要帶入iniconfig及HierarchicalConfiguration.Node instances,而建立key、value則是透過addProperty的方式! 最後就是add到iniconfig下,成為其children! 此時,另外save一config file(config_new.ini)
最後DEMO如下:
圖一
圖二(若不知怎設定可參考)
留言
張貼留言