您的位置:首页 > 编程语言 > Java开发

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

2015-05-08 16:43 519 查看
在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");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 读取配置