1. 程式人生 > >Java讀取XML配置檔案

Java讀取XML配置檔案

1.定義webConfiguration.xml檔案(名字隨取)
在這裡插入圖片描述
2.定義對應配置檔案實體類
import java.io.Serializable;//實現序列化介面是為方便轉成檔案,對應JSON
public class WebConfiguratinEntity implements Serializable{
private static final long serialVersionUID = 8355147750307144843L;
private String FolderPath;
public String getFolderPath() {
return FolderPath;
}
public void setFolderPath(String folderPath) {
FolderPath = folderPath;
}
}
3.測試類
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.AnyTypePermission;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestReadConfig {
//配置檔案路徑
private static String xmlPath=“com/config/webConfiguration.xml”;
public static void main(String args[]) throws Exception{
//TestReadConfig類與excel同級的,讀到相對路徑
//在resources目錄建立excel目錄並且隨便寫個檔案
String path=TestReadConfig.class.getClassLoader().getResource(“excel/”).getPath();
// 從配置檔案讀取資訊,讀到xml檔案FolderPath標籤的值,絕對路徑
private String FolderPath = TestReadConfig.readXML().getFolderPath();
}
/讀取配置檔案

/
public static WebConfiguratinEntity readXML(String xmlPath) throws Exception{
//建立XStream物件
XStream xs=new XStream();
//建立xml檔案緩衝流
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(TestReadConfig.class.getClassLoader().getResourceAsStream(xmlPath),“utf-8”));
StringBuilder sb=new StringBuilder();//建立StringBuilder物件
String temp=null;
while((temp=bufferedReader.readLine())!=null){
sb.append(temp);
}
String s=new String(sb);
XStream.setupDefaultSecurity(xs);
xs.addPermission(AnyTypePermission.ANY);
xs.alias(“config”,WebConfiguratinEntity.class);
WebConfiguratinEntity result=(WebConfiguratinEntity)xs.fromXML(s);
bufferedReader.close();
return result;
}
}