2014-07-01 57 views
0

我想读取位于我的代码的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(); 
} 

请指导什么是错,此代码和什么是读取外部属性文件的正确方法。

+0

可能重复(http://stackoverflow.com/questions/指定的文件2343187/loading-resources-using-getclass-getresource) – CMPS

回答

2

好吧,我想通了错误我自己。我将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自动查找到目录并加载通过[使用的getClass()加载资源.getResource()]的fileName

+1

我相信它应该是System.getProperty(“user.dir”)而不是getProperties。 – Maniek

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

使用ResourceBundle? –