Java读取src目录下的配置文件

在Java项目中,经常会用到一些全局配置,这些配置又有可能会改变,所以不应该写死在代码中,就用到了配置文件。

有两种格式可选择:xml和properties

样例分别如下:

1、db.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<entry key="url">
		<![CDATA[
	    	jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
		]]>
	</entry>
	<entry key="username">
		<![CDATA[
	    	root
		]]>
	</entry>
	<entry key="password">
		<![CDATA[
	    	root
		]]>
	</entry>
</properties>


2、db.properties

url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
username=root
password=root

读取方法如下:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 系统工具类
 *
 */
public class SystemUtils {
	/**
	 * 加载xml文件
	 * @param configFileName
	 * @return
	 * @throws IOException
	 */
	public static Properties loadConfigureFileXml(String configFileName) throws IOException {
		Properties props = new Properties();
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(configFileName);
			props.loadFromXML(inputStream);
		} finally {
			if (inputStream != null)
				inputStream.close();
		}
		return props;
	}

	/**
	 * 加载properties文件
	 * @param configFileName
	 * @return
	 * @throws IOException
	 */
	public static Properties loadConfigureFilePropertie(String configFileName) throws IOException {
		Properties props = new Properties();
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(configFileName);
			props.load(inputStream);
		} finally {
			if (inputStream != null)
				inputStream.close();
		}
		return props;
	}
}

调用方法示例:

pubic class Test{
    public static void main(String[] args){
        String xmlPath = Test.class.getResource("/db.xml").getPath();
	Properties sqlProperties = SystemUtils.loadConfigureFileXml(xmlPath);
	String url= sqlProperties.getProperty("url");
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值