GetResourceAsStream () returns null only in jar file

I know that the same question has been asked many times, but after going through all the answers already published, I could not find a solution.

First of all, here is the code that I use to check the problem after I met it in my project:

InputStream test;

System.out.println(this.getClass());
System.out.println(("classpath is: " + System.getProperty("java.class.path")));

test = getClass().getResourceAsStream("/pairs/images/100/back/back1.png");

if (test == null)
{
    System.out.println("getClass().getResourceAsStream(\"/pairs/images/100/back/back1.png\") is null");
    test = GridPanel.class.getClassLoader().getResourceAsStream("pairs/images/100/back/back1.png");
}

if (test == null)
{
    System.out.println("GridPanel.class.getClassLoader().getResourceAsStream(\"pairs/images/100/back/back1.png\") is null");
    test = ClassLoader.getSystemClassLoader().getResourceAsStream("pairs/images/100/back/back1.png");
}

if (test == null)
{
    System.out.println("ClassLoader.getSystemClassLoader().getResourceAsStream(\"pairs/images/100/back/back1.png\") is null");
    Thread.currentThread().getContextClassLoader().getResourceAsStream("pairs/images/100/back/back1.png");
}

if (test == null)
    System.out.println("Thread.currentThread().getContextClassLoader().getResourceAsStream(\"pairs/images/100/back/back1.png\") is null");

Thus, according to the header, each of these calls to getResourceAsStream () returns null, but only when the jar file is executed when launched inside the IDE (Netbeans 8.0.2), they all return the correct stream (not individually verified using this part of the code), and I can work with him.

Jar file contents: http://i.stack.imgur.com/1y8i8.png

While the src folder in the netbeans project folder looks like this: http://i.stack.imgur.com/AXj7s.png

, , netbeans, .

!

+4
3

TL; DR - NTFS,

, ...

Linux, , . InputStream, .

, - : Windows, , NTFS ( , , , ). , WORKED.

, ,

URL jarUrl = PairsDeck.class.getProtectionDomain().getCodeSource().getLocation();

jar, , ( ).

, , - , netbeans - NTFS.

File file = new File(jarUrl.toURI());
file.canWrite();
file.canRead();
file.canExecute(); 

true.

, , , Java.

!

0

, getResourceAsStream , ( , ). , , .

/, ?

0

.

  • Windows . .

  • The class getClass()determines in which jar / class path the resource is used. Especially if the unit test will not be placed in the jar, or the child class may be outside the jar. Either use SomeClassInJar.class, or use ClassLoader, which searches all jars / class paths. The class loader uses only absolute paths, and you should not run the path with /.

-1
source

All Articles