2013-06-26 41 views
0

嗨,我做了一个小程序,读取配置文件。该文件存储在实际的jar文件之外。与jar文件实际相同。 当我从实际目录中的命令行开始我的程序(即D:\ test \ java -jar name.jar argument0 argument1)时,它可以完美运行。文件未找到与外部文件的例外

但是,当我尝试从另一个位置运行程序,然后实际目录我得到了filenotfound异常(即D:\ java -jar D:\ test \ name.jar argument0 argument1)。

基本功能似乎工作,我做错了什么?

按照要求的代码的一部分:

public LoadConfig() { 
    Properties properties = new Properties(); 

    try { 
     // load the properties file 
     properties.load(new FileInputStream("ibantools.config.properties")); 

    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } // end catch 

    // get the actual values, if the file can't be read it will use the default values. 
    this.environment = properties.getProperty("application.environment","tst"); 
    this.cbc = properties.getProperty("check.bankcode","true"); 
    this.bankcodefile = properties.getProperty("check.bankcodefile","bankcodes.txt"); 
} // end loadconfig 

文件夹看起来是这样的: enter image description here

这工作: enter image description here

这不: enter image description here

该罐子不包含th e文本文件。

+1

大概你的代码(你没有给我们看)假定这个文件在当前目录中,但有时它不是;就那么简单。 –

+0

你可以给你正在使用的完整命令吗? – NightWhisper

+0

你能告诉我们一些代码吗?此外,你似乎在你的描述中回答自己的问题。 –

回答

2

当使用字符串/路径构造的FileFileInpustream等读取文件..相对路径从工作目录导出 - 在你开始你的程序的目录。

当从JAR文件读取,文件是外部罐子,你至少有两个选项:

  1. 提供绝对路径:D:/blah/foo/bar
  2. 让您的文件所在的目录部分类路径和使用this.getClass().getClassLoader().getResourceAsStream("myfile")

后者可能更适合读取存储在相对于应用程序位置的路径中的配置文件。