读写xml、properties 文件类型
新建java工程Test项目,项目src下建立demo.propertiesFileDemo.java、 demo.xmlFileDemo.java
引入相关jar包:
开始使用的是lang3 的jar 包,configurationException相关报错
后来查了一下居然是因为这个类里面定义的configurationException是继承了lang里面的NestableException 。
1.1 xml.java
package demo;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
public class xmlLoadDemo {
public static void main(String[] args){
try {
Configuration cfg = new XMLConfiguration("demo/config.xml");// 文件路径
String name = cfg.getString("Account.name");
System.out.println("name:"+ name);
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1.2 config.xml
<?xml version="1.0" encoding="gbk"?>
<Accounts>
<Account type="by0003">
<code>100001</code>
<pass>123</pass>
<name>李四</name>
<money>1000000.00</money>
</Account>
</Accounts>
2. properties demo
2.1 properties java
package demo;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
public class PropertiesFileDemo {
public static void main(String[] args) {
try {
Configuration cfg = new PropertiesConfiguration("demo/config.properties");
String name = cfg.getString("name");
System.out.println("name:"+ name);
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.2 config.properties
threads.max=50threas.min=2
timout=15.52
interactive=true
color=red
speed=50
name=Default User
3. java.until.properities 类使用
public class PropertiesFileDemo {
public static void main(String[] args) {
PropertiesFileDemo pfd = new PropertiesFileDemo();
pfd.getcfgFromUntilProperties();
}
public void getcfgFromUntilProperties(){
// PropertiesTest pt = new PropertiesTest();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("demo/config.properties");
System.out.println("begin!!!");
Properties properties = new Properties();
try{
properties.load(inputStream);
// properties.load(new FileInputStream("D:\\a.ini")); // 加载硬盘地址配置文件
}catch (IOException ioE){
ioE.printStackTrace();
}finally{
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("name:"+properties.getProperty("name"));
}
}