1. properties
# 键值对写法,要求键不相同,否者后者会覆盖前者account=rootusername=rootpassword=123# 层级键值对写法mysql.account=rootmysql.username=rootmysql.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);// 写入propertiesvoid 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=rootusername=rootpassword=123[redis]account=userusername=userpassword=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- v2mysql:data:account: rootusername: rootpassword: 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.documentDocument 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(); // 获取属性名;获取属性值
