我正在尝试读取位于我的代码的 jar 文件外部的属性。使用 ResourceBundle
但无法读取属性文件 locations.properties
。属性文件位于 resource
文件夹下,并且 jar
和 resource
文件夹位于同一目录下。
myDir
--> myJar.jar
--> resource
-->locations.properties
我不知道下面的代码有什么问题:
public static ResourceBundle getResourceBundle(String fileName) throws MalformedURLException{
if (resourceBundle == null) {
File file = new File("resource/"+fileName);
URL[] urls = { file.toURI().toURL() };
ClassLoader loader = new URLClassLoader(urls);
resourceBundle = ResourceBundle.getBundle(fileName, Locale.getDefault(), loader);
}
return resourceBundle;
}
这就是调用 ResourceBundle
对象的方式:
ResourceBundle locationBundle = null;
try {
locationBundle = ReadPropertyUtil.getResourceBundle(propFileName);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
请指导此代码有什么问题以及读取外部属性文件的正确方法是什么。
最佳答案
- 获取 Jar 文件路径。
- 获取该文件的父文件夹。
使用 InputStreamPath 中的该路径和您的属性文件名。
Properties prop = new Properties(); try { File jarPath=new File(YourClassNameInJar.class.getProtectionDomain().getCodeSource().getLocation().getPath()); String propertiesPath=jarPath.getParentFile().getAbsolutePath(); System.out.println(" propertiesPath-"+propertiesPath); prop.load(new FileInputStream(propertiesPath+"/resource/locations.properties")); } catch (IOException e1) { e1.printStackTrace(); }
关于java - 在 jar 之外找不到资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24503599/