2016-05-07 50 views
0

我在我的应用程序的类路径中有属性文件。在为这个应用程序创建jar文件之前,没有问题,但是当我创建jar文件并使用java -jar命令运行它时,它将返回null pointer exception。这里是我的代码来加载属性:如何访问jar文件中的文件?

private Properties loadProperties() { 
    Properties prop = new Properties(); 
    InputStream input = null; 

    try { 
     input = this.getClass().getResourceAsStream("./auth"); 
     prop.load(input); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } finally { 
     if (input != null) { 
      try { 
       input.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    return prop; 
} 

我可以访问jar文件中的属性文件或它是不可能的吗?

这里是例外,我得到:

Exception in thread "main" java.lang.NullPointerException 
    at java.util.Properties$LineReader.readLine(Properties.java:434) 
    at java.util.Properties.load0(Properties.java:353) 
    at java.util.Properties.load(Properties.java:341) 
    at com.kadir.MyApp.loadProperties(MyApp.java:109) 
    at com.kadir.MyApp.<init>(MyApp.java:62) 
    at com.kadir.MyApp.main(MyApp.java:48) 

和线路108和109是这些:

input =this.getClass().getClassLoader().getResourceAsStream("auth"); 
    prop.load(input); 

还要说明一点:我开发我的应用程序在Windows,但在Linux上运行它,错误可能来自这个

+4

在这里你去:http://stackoverflow.com/questions/5171957/access-file-in-jar-file –

+0

@RafaelOsipov我仍然收到空指针异常 – kadir

+0

什么是堆栈跟踪? –

回答

0

我不知道为什么它不工作的确切原因,但改变这两条线

input = this.getClass().getResourceAsStream("auth"); 
prop.load(input); 

这些:

ClassLoader classloader = Thread.currentThread().getContextClassLoader(); 
input = classloader.getResourceAsStream("auth"); 
prop.load(input); 

使我的代码工作