在实际开发工作的时候, 我们通常是将路径和文件的配置放在配置文件中, 这样的话,当我们有需要修改路径的时候, 就只需要去改那个配置文件就行了, 不需要到代码里面去一个一个地挨个去改, 但是我们究竟要怎么样才能获得这些配置文件里面的值呢?
其实这个操作是非常简单的, 我们只要封装如下的这一个大类作为工具类就可以了。
publicclassUrlUtil {
privatestaticProperties config =null;
static{
InputStream in = UrlUtil.class.getClassLoader().getResourceAsStream("url.properties");
config =newProperties();
try{
config.load(in);
in.close();
}catch(IOException e) {
//读取url.properties出错
e.printStackTrace();
}
}
/**
* 通过键获得对应的值
*@paramkey
*@return
*/
publicstaticString getValue(String key) {
try{
String value =config.getProperty(key);
returnvalue.trim();
}catch(Exception e) {
e.printStackTrace();
returnnull;
}
}
/**
* 读取properties的全部信息*/
publicstaticvoidgetAllProperties() {
try{
Enumeration en =config.propertyNames();
while(en.hasMoreElements()) {
String key =(String) en.nextElement();
String Property =config.getProperty(key);
}
}catch(Exception e) {
e.printStackTrace();
System.err.println("ConfigInfoError" +e.toString());
}
}
publicstaticvoidmain(String args[]) {
}
}
代码中的url.就是我们放置路径的配置文件。比如我们的url.中有个图片路径:=c:/
我们如果想要拿到这个值的话, 那么只需要直接去调用一个点号, 然后紧跟着用一对双引号包住空的内容就行。