项目中难免会用到一些业务相关的变量,有时可能需要根据项目的不同而去修改它的值,所以为了方便性以及可变性,这些需要写到一个配置文件中,
常用的有写在xml中,当然也有写成properties文件中的,本篇就是介绍如何读取properties中的值的。
这个properties中的特点和Map有点像,通过key=value的方式存储。
1、如果没有等号,则value为空
2、如果有多个等号,第一个等号之前的为key
3、如果以等号开始,就是key为空,value为等号后面的值了。
4、正常情况就是一个等号,并且等号前后都有值。
下面就是读取properties的代码,很简单的,其实就是读取文件了。
package com.jay.test.proeprties;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
public class PropertiesUtil {
public static void main(String[] args) {
readFromProperties("db.properties");
}
/**
* 从properties文件中读取数据
*
* @param filePath
*/
public static Properties readFromProperties(String filePath) {
InputStream in = PropertiesUtil.class.getResourceAsStream(filePath);
Properties properties = new Properties();
try {
properties.load(in);
Enumeration<?> enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String keyString = (String) enumeration.nextElement();
String valueString = (String) properties.getProperty(keyString);
System.out.println("key: " + keyString + " value: " + valueString);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return properties;
}
/**更新 value值或增加key--value
**/
public static Properties updateProperties(Map<String, String> keyValueString, String fileName) {
Properties properties = readFromProperties(fileName);
if (properties == null || keyValueString == null) {
return null;
}
try {
String pathString = PropertiesReaders.class.getClassLoader().getResource(fileName).getPath().toString();
//修改了目录中有空格转义为%20的原因。
URI uri = new URI(pathString);
OutputStream outputStream = new FileOutputStream(uri.getPath());
for(Iterator<Entry<String, String>> iterator=keyValueString.entrySet().iterator();iterator.hasNext();){
Entry<String, String> entry = iterator.next();
properties.put(entry.getKey(), entry.getValue());
} //修改多个key值时,需要最后才store下。否则会出问题的
properties.store(outputStream, "update linkproperties ");
outputStream.close();
} catch (FileNotFoundException e) {
properties = null;
} catch (IOException e) {
properties = null;
} catch (URISyntaxException e) {
properties = null;
}
return properties;
}
db.properties配置文件中的内容是
name=boy
value=eleven=
placechinese
=1344
name=girl
执行完代码后的效果如下所示:发现key相同后,后面的会覆盖之前的,这个就是和map特别像了。
key: name value: girl
key: placechinese value:
key: value value: eleven=
key: value: 1344
看了源代码之后,会发现Properties这个类继承了Hashtable,而去load文件流时,使用的是Hashtable的put方法,
所以为什么和map像这就不用多说了。