java读写ini文件
java读写ini文件
1、格式
INI文件由节、键、值组成。
节
[section]
参数
(键=值)
name=value
例:
[Total]
num=1
[Server]
ip=127.0.0.1
2、代码封装
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalINIConfiguration;
import org.apache.commons.configuration.SubnodeConfiguration;
import java.io.File;
public class IniFileUtil {
/**
* 获取属性值.
* @param path 文件路径
* @param section 节
* @param key 键
* @return 属性值
* @throws ConfigurationException ConfigurationException
*/
public static String getIniSectionKeyValue(String path, String section, String key) throws ConfigurationException {
HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(new File(path));
SubnodeConfiguration log = iniConfObj.getSection(section);
return log.getString(key);
}
/**
* 设置属性值.
* @param path 文件路径
* @param section 节
* @param key 键
* @param value 值
* @throws ConfigurationException ConfigurationException
*/
public static void setIniSectionKeyValue(String path, String section, String key, Object value) throws ConfigurationException {
HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(new File(path));
iniConfObj.setEncoding("UTF-8");
SubnodeConfiguration database = iniConfObj.getSection(section);
database.setProperty(key, value);
iniConfObj.save();
}
}