Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getResourceAsStream() work in the IDE but not the JAR?

I just want to read a file into my program. The file is located one directory above the working directory at "../f.fsh". So the following code runs correctly when I run it in the IDE

String name="../f.fsh";
InputStream is = getClass().getResourceAsStream(name);
InputStreamReader isreader=new InputStreamReader(is);//CRASHES HERE WITH NULL POINTER EXCEPTION
BufferedReader br = new BufferedReader(isreader);

but when I create a JAR file that has f.fsh zipped inside of it and run it, it crashes when creating the InputStreamReader, because the InputStream is null.

I've read a bunch of answers to questions about input streams and JAR files, and what I got out of it is that I should be using relative paths, but I am already doing that. From what I understand getResourceAsStream() can find files relative to the root of the project, that is what I want. Why does it not work in the JAR? What is going wrong, how can I fix it?

Does it have to do with the classpath? I thought that was only for including files external to the jar being run.

I have also tried, but still fail, when putting a slash in:

InputStream is = getClass().getResourceAsStream("\\"+name);

I looked at: How to get a path to a resource in a Java JAR file andfound that contents of a JAR may not necesarily be accesible as a file. So I tried it with copying the file relative to the jar (one directory up from the jar), and that still fails. In any case I'd like to leave my files in the jar and be able to read them there. I don't know what's going wrong.

like image 364
AAB Avatar asked Apr 16 '13 21:04

AAB


1 Answers

You can't use .. with Class.getResourceAsStream().

To load a resource f.fsh in the same package as the class, use SomeClass.class.getResourceAsStream("f.fsh")

To load a resource f.fsh in a sub-package foo.bar of the package of the class, use SomeClass.class.getResourceAsStream("foo/bar/f.fsh")

To load a resource f.fsh in any package com.company.foo.bar, use SomeClass.class.getResourceAsStream("/com/company/foo/bar/f.fsh")

This is described in the javadoc of the getResource() method, although it lacks examples.

like image 131
JB Nizet Avatar answered Oct 07 '22 13:10

JB Nizet