The getResourceAsStream function returns null, and getResource returns a URL

I ran into a very strange problem, I hope you can help me: I run the following line:

InputStream stream = this.getClass().getClassLoader().getResourceAsStream(SOME_PATH); 

And it works. Then I create a new classloader that points to the same file, and then

 this.getClass().getClassLoader().getResourceAsStream(SOME_PATH) 

returns null.

When I debug it, I saw that

 this.getClass().getClassLoader().getResource(SOME_PATH) 

returns a valid URL object.

So, I am debugging getResourceAsStream and see that it calls getResource, and when it tries to open steam - it does not work in FileNotFoundException.

I have no idea how to solve it. The stream is properly closed.

Is anyone

+4
source share
2 answers

ClassLoader.getResourceAsStream() will try to get the URL resource and make resource.openStream() .

It swallows any IOException and returns null . If you get a FileNotFoundException , it means that the resource was never found in the first place.

To check this, try:

 URL resource = this.getClass().getClassLoader().getResource(SOME_PATH); if (resource != null) { try { resource.openStream(); } catch (IOException e) { e.printStackTrace(); } } 

If you get any IOException , then ClassLoader.getResource() could not find the resource or could not open the stream by accident.

Hope this helps.

+2
source

I found a job (pay attention to setUseCaches):

  InputStream zipStream = null; URL resource = this.getClass().getClassLoader().getResource(SOME_PATH); if (resource != null) { try { URLConnection urlConnection = resource.openConnection(); urlConnection.setUseCaches(false); zipStream = urlConnection.getInputStream(); } catch (IOException e) { e.printStackTrace(); NolioAction._log.error(e.getMessage(), e); } } 
+1
source

All Articles