Robert Lu
Robert Lu

Reputation: 473

InputStream Cannot Be Null / Can't Access File Inside Another Package

I'm trying to access a file from one class inside another package inside a JAR file. To be more specific, the class in which I'm creating the inputstream is named ClassA.class and is located in the package: com.something.somethingelse while the file I'm trying to open with inputstream is located in the package com.something.storage. I'm calling the getResourceAsStream method as shown below:

    ClassA.class.getResourceAsStream("/com/something/storage/MyFile.txt");

However, it throws a IllegalArgumentException saying that the inputstream cannot be null. I've tried storing the text file in the same package as ClassA and the problem did not appear. Only when it's stored in another package does this occur. Please help.

It might also be helpful to know that the method I'm doing this in is a static one. Will that have anything to do with the problem?

Upvotes: 4

Views: 8906

Answers (2)

alain.janinm
alain.janinm

Reputation: 20065

In your class inside com.something.somethingelse open the stream with :

getClass().getClassLoader().getResourceAsStream("com/something/storage/MyFile.txt");

Using getClassLoader() you specify the package path in an absolute way (without the first /).

Upvotes: 3

mulax
mulax

Reputation: 219

ClassA.class.getResourceAsStream("/com/something/storage/MyFile.txt");

returns null because the file "/com/something/storage/MyFile.txt" does not exist

Upvotes: 1

Related Questions