java读取配置文件( properties 与 xml )

本文介绍了如何使用Java读取properties和xml两种类型的配置文件,并提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、读取properties文件:

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 {

		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mpxj.properties");  //将配置文件读取到输入流中
		Properties properties = new Properties();  
		try{  
			properties.load(inputStream);  //加载配置文件
		}catch (IOException ioE){  
			ioE.printStackTrace();  
		}finally{  
			inputStream.close();  
		}  
		return properties.getProperty("name"); //根据配置文件properties的name获取value
	}
	
}
配置文件如下:
name        value
name        e:\test.mpp

二、读取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配置文件








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值