0

I am trying to read a text file from within the JAR archive of my program. I am getting a null pointer exception when I call the method. I can't find many examples of how to do this that work online, they are all much like what I am using.

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.");
        }
    }
}

I get this error when I try to run this code: $ 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
cyrus
  • 51
  • 1
  • 5
  • The error indicates that the desired resource is not available. And SO has [a lot of questions](http://stackoverflow.com/search?q=getResourceAsStream) about `getResourceAsStream()`. – kdgregory Jun 02 '14 at 21:44
  • What is the project structure where this file is present? – Braj Jun 02 '14 at 21:46
  • I have answered it [here](http://stackoverflow.com/questions/23506089/how-to-add-txt-file-to-a-jtextarea-and-where-to-place-my-txt-file/23506266#23506266) somewhat in the same context. It might help you to understand the project structure and `getResourceAsStream()` – Braj Jun 02 '14 at 21:48

1 Answers1

1

Open the jar with 7zip, WinZip or so. And check the path "/data/cmdhelp". This must be case sensitive.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • I see what happened, additional source folders in eclipse have the same path. So the path to it for getResourceAsStream was /cmdhelp not /data/cmdhelp. – cyrus Jun 02 '14 at 21:44