使用getResourceAsStream的InputStreamReader的NullPointerException

时间:2014-06-02 21:38:33

标签: java nullpointerexception inputstreamreader

我正在尝试从我的程序的JAR存档中读取文本文件。当我调用该方法时,我得到一个空指针异常。我无法找到许多如何在线工作的例子,它们就像我正在使用的那样。

public class ConsoleHelp {
    public void print() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/data/cmdhelp")));

            int c;
            do {
                c = reader.read();
                System.out.print((char) c);
            } while (c > -1);
            System.out.println();
        } catch (IOException e) {
            System.out.println("JAR file has not been packaged correctly.");
        }
    }
}

尝试运行此代码时出现此错误: $ java -jar accface-0.1-test8.jar help

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.NullPointerException
        at java.io.Reader.<init>(Reader.java:78)
        at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
        at frontend.ConsoleHelp.print(ConsoleHelp.java:11)
        at frontend.Command.main(Command.java:112)
        ... 5 more

1 个答案:

答案 0 :(得分:1)

用7zip,WinZip等打开jar。并检查路径“/ data / cmdhelp”。这必须区分大小写。