1

I need the URI of a file (which I put in the resources directory). If I use

MyClass.class.getClassLoader().getResource(resource)

I get

java.lang.IllegalArgumentException: URI is not hierarchical

Otherwise, if I use ClassLoader.getSystemResource(resource) it returns null.

The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
user2733845
  • 43
  • 1
  • 1
  • 7

2 Answers2

1

Are you loading the file from inside a jar? If so, the OS is unable to form a java File instance from inside a jar. To be able to load it, try open it as a Stream. "filepath" should start with a "/".

MyClass.class.getClass().getResourceAsStream( filepath );
Peter Kennedy
  • 541
  • 6
  • 11
-1

You should be using

getResourceAsStream(...);

when the resource is bundled as a jar/war or any other single file package for that matter.

See the thing is, a jar is a single file (kind of like a zip file) holding lots of files together. From Os's pov, its a single file and if you want to access a part of the file(your image file) you must use it as a stream.

Raj Hirani
  • 182
  • 1
  • 5
  • Can you please provide sources for your answers. I think your answer got downvoted exactly for this, cause it is an almost exact copy of another user's answer: https://stackoverflow.com/a/18055478/19032206 – qaziqarta Dec 02 '22 at 05:59