java專案中配置檔案的使用
讀寫xml、properties 檔案型別
新建java工程Test專案,專案src下建立demo.propertiesFileDemo.java、 demo.xmlFileDemo.java
引入相關jar包:
:commons-collections-3.2.jar、commons-configuration-1.6.jar、commons-lang-2.4.jar和commons-logging-1.2.jar。
開始使用的是lang3 的jar 包,configurationException相關報錯
後來查了一下居然是因為這個類裡面定義的configurationException是繼承了lang裡面的NestableException
1.xml Demo
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"));
}
}