【问题标题】:Can't find resource outside the jar在 jar 之外找不到资源
【发布时间】:2014-08-21 14:52:43
【问题描述】:

我正在尝试读取位于我的代码的 jar 文件外部的属性。使用 ResourceBundle 但它无法读取属性文件 locations.properties。属性文件位于resource文件夹下,jarresource文件夹在同一目录下。

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

请指导这段代码有什么问题以及读取外部属性文件的正确方法是什么。

【问题讨论】:

标签: java resourcebundle properties-file


【解决方案1】:

好吧,我自己发现了错误。我将文件名附加到目录位置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 指定的文件

【讨论】:

  • 我相信它应该是 System.getProperty("user.dir") 而不是 getProperties。
【解决方案2】:
  1. 获取 Jar 文件路径。
  2. 获取该文件的父文件夹。
  3. 在 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();
        }
    

【讨论】:

  • 使用 ResourceBundle?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 2012-02-04
相关资源
最近更新 更多