1. properties
# 键值对写法,要求键不相同,否者后者会覆盖前者
account=root
username=root
password=123
# 层级键值对写法
mysql.account=root
mysql.username=root
mysql.password=123
import java.io.*;
import java.util.Enumeration;
import java.util.Properties;
// 内置函数无需调用
// Properties说明
public Properties(); // 创建空属性列表
void load(InputStream inStream); // 从字符输入流中读取属性列表
String getProperty(String key); // 获取指定键值
void store(OutputStream out, String comments);// 写入properties
void clear(); // 清除所以键值对
// Properties单信息读取
public static String readValue(String filePath, String key){
Properties props = new Properties();
try{
InputStream in = new BufferedInputStream (new FileInputStream(filePath));
props.load(in);
return props.getProperty(key);
}catch(Exception e){
e.printStackTrace();
return null;
}
}
// properties多信息查看
public static void printAllPropperties(String filePath){
Properties props = new Properties();
try{
InputStream in = new BufferedInputStream (new FileInputStream(filePath));
props.load(in);
Enumeration en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String)en.nextElement();
System.out.println(key + " : " + props.getProperty(key));
}
}catch(Exception e){e.printStackTrace();}
}
// properties写入
public static void writeProperties(String filePath, String key, String value){
Properties prop = new Properties();
try{
InputStream fis = new FileInputStream(filePath);
prop.load(fis);
OutputStream fos = new FileOutputStream(filePath);
prop.setProperty(key, value);
prop.store(fos, "Update '" + key + "' value");
}catch(IOException e){
System.err.println("Visit "+filePath+" for updating "+key+" value error");
}
}
2. ini
[mysql]
account=root
username=root
password=123
[redis]
account=user
username=user
password=456
IniFileHelper inifile = new IniFileHelper( GlobalSetting.AppPath + "\\file.ini");
MessageBox.Show(GlobalSetting.AppPath);
String mysqlAccount = inifile.IniReadValue("mysql", "account");
String mysqlUsername = inifile.IniReadValue("mysql", "username");
String mysqlPpassword = inifile.IniReadValue("mysql", "password");
3. yaml / yml
mq:
data:
xx:
- v1
- v2
mysql:
data:
account: root
username: root
password: 123
4. xml
lib.keyxml所需jar,将后缀改成7z
<?xml version="1.0" encoding="utf-8" ?>
<mysql>
<account id="xx">root</account>
<username>root</username>
<password>123</password>
</mysql>
//1·加载文件
InputStream stream = test.class.getClassLoader()
.getResourceAsStream("info.xml");
//2.创建dom4j的解析器
SAXReader saxReader = new SAXReader();
//3.处理xml文件流 xml -> java.document
Document document = saxReader.read(stream);
//4.xpath语法,寻找所需标签
// 元素标签 / -> 从匹配根标签
Element username = (Element)document.selectSingleNode("/mysql/username");
System.out.println(username.getText());
// 元素标签集, // -> 匹配所有标签
List<Element> password = document.selectNodes("//password");
System.out.println(password.get(0).getText());
// 属性找标签
Attribute id = element.attribute("id"); // 获取属性
id.getName;id.getValue(); // 获取属性名;获取属性值