[英]Can't find resource outside the jar
我试图使用ResourceBundle
读取位于代码的jar文件外部的属性,但无法读取属性文件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();
}
请指导这段代码有什么问题以及什么是读取外部属性文件的正确方法。
在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(); }
好吧,我自己找出了错误。 我将fileName附加到目录位置File file = new File("resource/"+fileName);
这是错误的。
我要做的就是首先使用获取当前的工作目录名称
System.getProperties("user.dir") //this gives me the path of my current directory
并将仅目录名称传递给文件对象。
File file = new File("resource/");
然后使用指定的文件名加载捆绑软件。
resourceBundle = ResourceBundle.getBundle(fileName, Locale.getDefault(), loader);
ResourceBundle自动查找目录并加载由fileName
指定的文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.