2015-02-09 133 views
0

我有一個項目,我將其轉換爲可運行jar文件。我正在使用ini4j在我的ini文件中存儲一些配置。將.ini文件轉換爲可運行jar文件時

它工作時,我簡單地設置目錄getConf = new Ini(new FileReader(path));,但它不會工作,當我使用getResourceAsStream()

public class IniReader { 

// When I set it like that, it works.. 
private static String path = "../conf.ini"; 

public static String readIni(String val, String getOb, String fetchOb) { 
    Ini getConf = null; 

    try { 
    // When I set it like that, it works.. 
     getConf = new Ini(new FileReader(path)); 

     // I want to use this version but I am getting null error. 
     //getConf = new Ini(new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf.ini")))); 

    } catch (InvalidFileFormatException e) { 
     System.err.print("Error InvalidFileFormat : " + e.getMessage() + "\n"); 
     e.printStackTrace(); 
    } catch (FileNotFoundException e) { 
     System.err.print("Error FileNotFoundException : " + e.getMessage() + "\n"); 
     e.printStackTrace(); 
    } catch (IOException e) { 
     System.err.print("Error IOException : " + e.getMessage() + "\n"); 
     e.printStackTrace(); 
    } 
    return val = getConf.get(getOb).fetch(fetchOb); 
} 

當我嘗試閱讀我的ini文件我收到以下錯誤;

Exception in thread "main" java.lang.NullPointerException 
    at java.io.Reader.<init>(Reader.java:78) 
    at java.io.InputStreamReader.<init>(InputStreamReader.java:113) 
    at org.ini4j.Ini.load(Ini.java:104) 
    at org.ini4j.Ini.<init>(Ini.java:56) 
    at com.test.ttf.IniReader.readIni(IniReader.java:28) 
    at com.test.ttf.SlashSCR.InitProg(SlashSCR.java:116) 
    at com.test.ttf.InitProg.main(InitProg.java:18) 

這是我想讀.ini文件

enter image description here

編輯

我也試過以下;

Ini getConf= new Ini(); 
    getConf.load(Thread.currentThread().getContextClassLoader().getClass().getResourceAsStream("../conf.ini")); 

回答

1

如果要加載從罐子的配置,您可以使用路徑getResource()getResourceAsStream()功能。 的NullPointerException指示(最有可能的,因爲它總是很難用在一行上許多語句來告訴),該資源未找到(它默認返回null

如果你想從本地文件加載它,然後你只需要使用原始方法(使用FileReader)。但是,您必須設置相對於執行目錄的路徑(您從中運行java)。這很可能與您的jar相同。在這種情況下,您應該使用"conf.ini"而不是"../conf.ini"

+0

謝謝!我打算製作這個文件的.exe和.app版本,我應該將我的.ini文件放在資源目錄中,並在exe和app文件旁邊生成快捷方式,或者我應該直接讓用戶通過原始文件訪問ini文件目錄? – 2015-02-09 13:47:31

+0

這並不重要,只要它們與運行位置相比處於相同的相對位置即可。當您使用快捷方式時,設置運行目錄是快捷方式的一個屬性(所以這可能會使它更復雜一點)。 – Thirler 2015-02-09 14:11:25