2013-06-26 112 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")

後者可能更適合讀取存儲在相對於應用程序位置的路徑中的配置文件。