转换为Runnable Jar文件时读取.ini文件

时间:2015-02-09 13:29:47

标签: java bufferedreader filereader ini ini4j

我有一个项目,我将把它转换为runnable jar文件。我使用ini4j在我的ini文件中存储了一些配置。

当我只设置目录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);
}

当我尝试阅读我的iniFile时,我收到以下错误;

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 个答案:

答案 0 :(得分:1)

如果要从jar加载配置,可以使用路径getResource()getResourceAsStream()函数。 NullPointerException表示(很可能,因为在一行上很难说很多语句)资源未找到(默认返回null

如果要从本地文件加载它,那么您只需使用原始方法(使用FileReader)。但是,您必须设置相对于执行目录的路径(从中运行java的位置)。这很可能与您的jar目录相同。在这种情况下,您应该使用"conf.ini"而不是"../conf.ini"

相关问题