简体   繁体   English

在罐子外面找不到资源

[英]Can't find resource outside the jar

I am trying to read properties which is located external to the jar file of my code.using ResourceBundle but its unable to read the property file locations.properties . 我试图使用ResourceBundle读取位于代码的jar文件外部的属性,但无法读取属性文件locations.properties The property file is located under resource folder and both jar and resource folder are under same directory. 该属性文件位于resource文件夹下,而jarresource文件夹都位于同一目录下。

myDir

   --> myJar.jar
   --> resource
          -->locations.properties

I don't know whats wrong with my code below: 我不知道下面的代码有什么问题:

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;
}

And this is how am invoking ResourceBundle object: 这就是调用ResourceBundle对象的方式:

ResourceBundle locationBundle = null;
try {
    locationBundle = ReadPropertyUtil.getResourceBundle(propFileName);
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Please guide whats wrong with this code and whats the correct way of reading an external properties file. 请指导这段代码有什么问题以及什么是读取外部属性文件的正确方法。

  1. Get Jar file path. 获取Jar文件路径。
  2. Get Parent folder of that file. 获取该文件的父文件夹。
  3. Use that path in InputStreamPath with your properties file name. 在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(); } 

Well, I figured out the error myself. 好吧,我自己找出了错误。 I was appending the fileName to the directory location File file = new File("resource/"+fileName); 我将fileName附加到目录位置File file = new File("resource/"+fileName); which was wrong. 这是错误的。

All I had to do was to first get the present working directory name using 我要做的就是首先使用获取当前的工作目录名称

System.getProperties("user.dir")   //this gives me the path of my current directory

and passing only the directory name to file object. 并将仅目录名称传递给文件对象。

File file = new File("resource/");

And then load the bundle using the specified file name. 然后使用指定的文件名加载捆绑软件。

resourceBundle = ResourceBundle.getBundle(fileName, Locale.getDefault(), loader);

ResourceBundle automatically looks into the directory and loads the file specified by the fileName ResourceBundle自动查找目录并加载由fileName指定的文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM