我有一个项目,我要把它转换成可运行的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文件的地方

编辑
我还试了以下几种方法;
Ini getConf= new Ini();
getConf.load(Thread.currentThread().getContextClassLoader().getClass().getResourceAsStream("../conf.ini"));发布于 2015-02-09 13:38:35
当您想从jar加载配置时,可以使用路径getResource()和getResourceAsStream()函数。NullPointerException表示(很可能是因为总是很难用一行多条语句判断)没有找到资源(它静默地返回null)。
如果希望从本地文件加载它,那么只需使用原始方法(使用FileReader)即可。但是,您必须设置相对于执行目录(运行java的位置)的路径。这很可能是与jar相同的目录。在这种情况下,您应该使用"conf.ini"而不是"../conf.ini"。
https://stackoverflow.com/questions/28410928
复制相似问题