在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>
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");
}
}