程序中配置文件如果放在classes文件夹,就可以使用class下的getResource().getPath();获取文件路径。
默认情况下eclipse以bin文件夹为编译后的输出文件夹,所以要使用PropertyConfiguiator.configure读取配置文件时,需要把bin文件夹名称替换成config配置文件,栗子:
public static void main(String[] args) {
String path = Worker.class.getResource("/").getPath();
//System.out.println("path = " + path); //path = /E:/workspace/Task/bin/
path = path.substring(1).replace("bin", "config");
//System.out.println("path = " + path); //path = E:/workspace/Task/config/
PropertyConfigurator.configure (path + "properties/log4j.properties");
ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
//System.out.println("springApplication:" + context);
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
如果文件路径中存在空格,URLEncode后的路径空格会变成20%,需要将path进行一次URLDecode
path = URLDecoder.decode(path, chartset);