一、Java Properties类
Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件。
它提供了几个主要的方法:
1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
二、代码实现
例如,取配置文件中ufop.local-storage-path的值:
@RequestMapping(value = "test", method = RequestMethod.GET)
public String index() {
//读取配置文件中 ufop.local-storage-path的值
return getvalue("ufop.local-storage-path");
}
//读取出配置文件中的文件存储根目录,然后进行存储操作
public static String getvalue(String key) {
Properties p = new Properties();
FileInputStream fis;
//获取位于工程根目录下的config.properties配置文件绝对路径
String url = new File("").getAbsolutePath() + File.separator + "/src/main/resources/config/application.properties";
try {
fis = new FileInputStream(url);
// load 从输入流中读取属性列表(键和元素对)。通过对指定的文件
//(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索
p.load(fis);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.print("problems with properties");
e.printStackTrace();
}
//用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value
return p.getProperty(key);
}