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

I just want to read the file in my program. The file is located in one directory above the working directory "../f.fsh". So the following code works 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 with f.fsh, zipped inside it and starting it, it fails to create an InputStreamReader, because InputStream is null.

I read a bunch of answers to questions about input streams and JAR files, and I realized that I should use relative paths, but I already do this. As far as I understand, getResourceAsStream () can find files relative to the project root, this is what I want. Why does this not work in a JAR? What is wrong, how can I fix it?

Is this related to classpath? I thought that this was only to include files external to a working bank.

I also tried, but still fail when I put the slash:

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

I looked: How to get the resource path in a Java JAR file and found that the contents of the JAR may not necessarily be available as a file. Therefore, I tried it with copying the file in relation to the bank (one directory from the bank), and this still fails. In any case, I would like to leave my files in the bank and be able to read them there. I do not know what's happening.

+6
source share
2 answers

If .. works in Class.getResourceAsStream() while working from Eclipse, this is a bug in Eclipse. Eclipse and other IDEs implement custom classloaders to fetch resources from a project at runtime. It seems that the implementation of the class loader in Eclipse does not perform all the necessary checks on the input of the getResourceAsStream() method. In this case, the error is in your favor, but you still need to rethink how you structure your resources so that your code works in all cases.

+3
source

You cannot use .. with Class.getResourceAsStream() .

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

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

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

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

+8
source

All Articles