1. 程式人生 > >java讀取配置檔案( properties 與 xml )

java讀取配置檔案( properties 與 xml )

public class Properties{
	public static void main(String[] args){

		Properties pt = new Properties();//建立一個Properties物件
			
		try {
			String url = pt.getProperties();//呼叫Properties物件的getProperties()方法,接收方法返回的配置檔案路徑
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	private String getProperties() throws IOException,
			ParserConfigurationException, SAXException {

		String value = null;//用於返回xml檔案的路徑
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//建立DocumentBuilder工廠
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();//建立Document物件
			Document doc = db
					.parse("D:/test.xml");//獲取xml配置

			NodeList jarList = doc.getElementsByTagName("jar");//由於xml檔案的資料結構是樹的結構,所以可將其放入結
			for (int i = 0; i < jarList.getLength(); i++) {
				Node jar = jarList.item(i);//返回集合中的第i項
				Element elem = (Element) jar;
				for (Node node = jar.getFirstChild(); node != null; node = node
						.getNextSibling()) {
					value = node.getNodeValue();//獲取標籤內容
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}
}
配置檔案如下:
<jar id="tt" >e:\Dcits\2018.1.11—研發計劃\SmartTeller10研發計劃_V0.1.mpp</jar>

注:使用properties配置檔案時,使用文字編輯器開啟伺服器上的配置檔案時,中文字元等會亂碼,所以最好使用xml配置檔案