-1

I noticed that the .getResource() method doesn't work when loading a text file from an executable jar file when using a class loader (even though it works fine for ImageIcon instances). But, the .getResourceAsStream() method works perfectly fine for text files. Why is this? In general, which procedure is the better one to use and why? Thanks!

Doesn't work

File f = new File(this.getClass().getClassLoader().getResource().toString());

Works

InputStream input = new InputStreamReader(this.getClass().getClass.Loader().getResourceAsStream());
Calculus5000
  • 427
  • 6
  • 17
  • 1
    Of course it doesn't work. The resource is in the jar file, not on the file system. So the URL you get is not the URL of a file. It's the URL of a resource inside a jar file. – JB Nizet Feb 18 '15 at 16:16

1 Answers1

1

The reason of the fact that first method doesn't work isn't in the getResource() method...it doesn't work because File cannot reference a file within jar file. Please remember that File is an object designed to communicate with file system, but it cannot look inside a jar file (which is zip file).

On the other hand getResourceAsStream() opens a InputStream to the resource, giving you a chance to access directly to its bytes content.

By the way URL object returned by getResource method is still a valid "pointer" to the resource, it is the File implementation that cannot use this reference, because it's out of his scope.

cigno5.5
  • 703
  • 4
  • 13