【问题标题】:Reading .ini File When Converted into Runnable Jar File转换为可运行 Jar 文件时读取 .ini 文件
【发布时间】:2015-04-09 06:15:41
【问题描述】:

我有一个项目,我要把它转换成可运行的 jar 文件。我使用ini4j 将一些配置存储在我的i​​ni 文件中。

当我简单地设置目录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 文件的地方

编辑

我也尝试了以下方法;

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

【问题讨论】:

    标签: java bufferedreader filereader ini ini4j


    【解决方案1】:

    当您想从 jar 加载配置时,可以使用路径 getResource()getResourceAsStream() 函数。 NullPointerException 表示(很可能,因为总是很难用一行上的许多语句来判断)找不到资源(它默默地返回 null

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

    【讨论】:

    • 谢谢!我要制作这个文件的 .exe 和 .app 版本,我应该将我的 .ini 文件放在资源目录中并在 exe 和 app 文件旁边生成快捷方式,还是应该直接让用户通过相同的原始文件访问 ini 文件目录?
    • 这无关紧要,只要它们与运行位置相比位于相同的相对位置即可。当您使用快捷方式时,设置运行目录是快捷方式的一个属性(因此这可能会使它更复杂一些)。
    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 2020-02-27
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2015-10-02
    • 1970-01-01
    相关资源
    最近更新 更多