一、properties文件介绍
java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是 "键=值"的格式,在properties文件中,可以用"#"来作注释,properties文件在Java编程中用到的地方很多,操作很方便。
properties文件示例:
# 以下为服务器、数据库信息
dbPort = localhost
databaseName = mydb
dbUserName = root
dbPassword = root
# 以下为数据库表信息
dbTable = mytable
# 以下为服务器信息
ip = 192.168.0.9
上面的文件中我们假设该文件名为:test.properties 文件。其中# 开始的一行为注释信息;在等号“= ”左边的我们称之为key ;等号“= ”右边的我们称之为value 。(其实就是我们常说的键- 值对)key 应该是我们程序中的变量。而value 是我们根据实际情况配置的。
二、java常见读取properties文件方法
1、使用java.util.Properties类的load()方法示例:
- InputStream in = lnew BufferedInputStream(new FileInputStream(name));
- Properties p = new Properties();
- p.load(in);
<span style="font-size:14px;"><span style="font-size:14px;">InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);</span></span>
2、使用java.util.ResourceBundle类的getBundle()方法
示例:
- ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
<span style="font-size:14px;"><span style="font-size:14px;">ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault()); </span></span>
用ResourceBundle读取.properties文件可避免路径问题
我在jar里读取.properties文件时,总是找不到文件路径,后来用ResourceBundle读取.properties文件即可避免路径问题,代码如下:
//process为文件名,切记不要加 .properties, URL是文件里的键名
- ResourceBundle bundle = ResourceBundle.getBundle("com.ihandy.smsoc.app.process");
- String s = bundle.getString("URL");
- System.out.println(s);
- pURL = s;
<span style="font-size:14px;"><span style="font-size:14px;"> ResourceBundle bundle = ResourceBundle.getBundle("com.ihandy.smsoc.app.process");
String s = bundle.getString("URL");
System.out.println(s);
pURL = s;</span></span>
3、使用java.util.PropertyResourceBundle类的构造函数
示例:
- InputStream in = new BufferedInputStream(new FileInputStream(name));
- ResourceBundle rb = new PropertyResourceBundle(in);
<span style="font-size:14px;"><span style="font-size:14px;">InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in); </span></span>
4、使用class变量的getResourceAsStream()方法
示例:
- InputStream in = 类名.class.getResourceAsStream(name);
- Properties p = new Properties();
- p.load(in);
<span style="font-size:14px;"><span style="font-size:14px;">InputStream in = 类名.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in); </span></span>
5、使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法示例:
- InputStream in = 类名.class.getClassLoader().getResourceAsStream(name);
- Properties p = new Properties();
- p.load(in);
<span style="font-size:14px;"><span style="font-size:14px;">InputStream in = 类名.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in); </span></span>
6、使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法示例:
- InputStream in = ClassLoader.getSystemResourceAsStream(name);
- Properties p = new Properties();
- p.load(in);
<span style="font-size:14px;"><span style="font-size:14px;">InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in); </span></span>
7、Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法示例:
- InputStream in = context.getResourceAsStream(path);
- Properties p = new Properties();
- p.load(in);
假如我现在有一个数据库的配置文件,我将它写为资源文件的样式,则为:
1
2
3
4
5
| #数据库配置信息
DRIVER=com.mysql.jdbc.Driver
URL=jdbc:mysql://localhost:3306/cns
user=test
password=test
|
接下来,我们使用ResourceBundle类处理:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| package Forum;
import java.util.*;
public class RedProFile {
public static void main(String[] a){
String resourceFile = "Forum.CNS";
// 创建一个默认的ResourceBundle对象
// ResourceBundle会查找包Forum下的CNS.properties的文件
// Forum是资源的包名,它跟普通java类的命名规则完全一样:
// - 区分大小写
// - 扩展名 .properties 省略。就像对于类可以省略掉 .class扩展名一样
// - 资源文件必须位于指定包的路径之下(位于所指定的classpath中)
// 假如你是在非Web项目中使用,则一定要写资源文件的路径,也就是包路径必须存在。
// 如果是Web项目,不写包路径可以,此时将资源文件放在WEB-INF\classes\目录下就可以。
ResourceBundle rb = ResourceBundle.getBundle(resourceFile);
System.out.println(rb.getString("DRIVER"));//这里是分大小写的,嘿嘿输出值为jdbc:mysql://localhost:3306/cns
}
}
|
可以这样写的原因,看下面源码
/**
* Converts the given <code>bundleName</code> to the form required
* by the {@link ClassLoader#getResource ClassLoader.getResource}
* method by replacing all occurrences of <code>'.'</code> in
* <code>bundleName</code> with <code>'/'</code> and appending a
* <code>'.'</code> and the given file <code>suffix</code>. For
* example, if <code>bundleName</code> is
* <code>"foo.bar.MyResources_ja_JP"</code> and <code>suffix</code>
* is <code>"properties"</code>, then
* <code>"foo/bar/MyResources_ja_JP.properties"</code> is returned.
*
* @param bundleName
* the bundle name
* @param suffix
* the file type suffix
* @return the converted resource name
* @exception NullPointerException
* if <code>bundleName</code> or <code>suffix</code>
* is <code>null</code>
*/
public final String toResourceName(String bundleName, String suffix) {
StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length());
sb.append(bundleName.replace('.', '/')).append('.').append(suffix);
return sb.toString();
}
最终还是用classloader进行资源文件的加载:
else if (format.equals("java.properties")) {
final String resourceName = toResourceName0(bundleName, "properties");
if (resourceName == null) {
return bundle;
}
final ClassLoader classLoader = loader;
final boolean reloadFlag = reload;
InputStream stream = null;
try {
stream = AccessController.doPrivileged(
new PrivilegedExceptionAction<InputStream>() {
public InputStream run() throws IOException {
InputStream is = null;
if (reloadFlag) {
URL url = classLoader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
// Disable caches to get fresh data for
// reloading.
connection.setUseCaches(false);
is = connection.getInputStream();
}
}
} else {
is = classLoader.getResourceAsStream(resourceName);
}
return is;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getException();
}
if (stream != null) {
try {
bundle = new PropertyResourceBundle(stream);
} finally {
stream.close();
}
}
} else {
throw new IllegalArgumentException("unknown format: " + format);
}
并且最终 还是使用了java类Properties
public PropertyResourceBundle (InputStream stream) throws IOException {
Properties properties = new Properties();
properties.load(stream);
lookup = new HashMap(properties);
}