日期:2014-05-20  浏览次数:20851 次

单例模式读取配置文件,如果打成jar包,会出现FileNotFoundExcpetion,有没有什么好的解决方法?
该程序的目的是实现只有一个ConfigManager 实例在程序中,只有properties配置文件修改日期变化后(也就是修改了)才再重新加载并且读取配置文件,properties配置文件也在com.liuccc.util包中


package com.liuccc.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


public class ConfigManager {
private static final String FILENAME = "config.properties";
private long lastModifiedTime = 0;
private Properties props = null;
private File file = null;
private String filepath = null;
private static ConfigManager cm = new ConfigManager();

private ConfigManager(){
URL url = ConfigManager.class.getResource(FILENAME);
filepath = url.getFile();
file = new File(filepath);
lastModifiedTime = file.lastModified();
props = new Properties();
try {
props.load(new FileInputStream(filepath));
} catch (Exception e) {
e.printStackTrace();

}

synchronized public static ConfigManager getInstance(){
return cm;
}

public Map getConfigItem(){
long newTime = file.lastModified();
Map<String,String> map = null;
if(newTime != lastModifiedTime){
props.clear();
try {
props.load(new FileInputStream(filepath));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
lastModifiedTime = newTime;
map = new HashMap<String,String>();
Object[] keys = props.keySet().toArray();
String tempKey = "";
for(int i = 0;i < keys.length;i++){
tempKey = keys[i].toString();
map.put(tempKey, props.get(tempKey).toString().trim());
}
return map;
}
}
现在的问题是如果我把该ConfigManager.java和properties文件打包成util.jar包(项目需要必须打包)后,new FileInputStream(filepath))会报异常,找不到比如D:\util.jar\com\liuccc\util.jar\config.properties,但是不打成jar包一切正常
我知道有ConfigManager.class.getResourceAsStream可以解决部分问题,但是获取文件修改时间:file = new File(filepath);
lastModifiedTime = file.lastModified();必须要 new File(filepath);
有没有朋友知道解决方法????


------解决方案--------------------
还有,对于你这个需求:
引用楼主 liuccc1 的帖子:
只有properties配置文件修改日期变化后(也就是修改了)才再重新加载并且读取配置文件
...
ConfigManager.java和properties文件打包成util.jar包

------解决方案--------------------
开始的时候也是转成URI的方式,调试没问题,

把你jar里面调用的语句贴上来,记得绝对不能用什么绝对路径,要用相对路径