[Logo]
Forums Register Login
class.getResource()
When I have a line of code like the following:



Where is the file system does Java expect to find this file.

Thanks,

Jerry
Relative to the classpath.
It's not just relative to the classpath - it also incorporates the package of the Class. So if your classpath is C:\Java\src;C:\Java\classes, and TextSampleDemo is in package foo.bar, then there are two possible places the gif may be found:

C:\Java\src\foo\bar\images\sound.gif
C:\Java\classes\foo\bar\images\sound.gif

Note that this is assuming that the current ClassLoader is still the system class loader. Of other class loaders are involved, they may search additional locations, according to whatever rules those class loaders follow. But they should let their parent loader search first, so if the system class loader can find the resource at one of the two locations shown above, then any additional class loaders are irrelevant. Anyway, this is a simplified discussion of class loaders - interested parties should read up on the documentation for them. I just wanted to note that different class loaders can change some of the rules stated so far.
 

Originally posted by Jim Yingst:

Note that this is assuming that the current ClassLoader is still the system class loader. Of other class loaders are involved, they may search additional locations, according to whatever rules those class loaders follow. But they should let their parent loader search first, so if the system class loader can find the resource at one of the two locations shown above, then any additional class loaders are irrelevant. Anyway, this is a simplified discussion of class loaders - interested parties should read up on the documentation for them. I just wanted to note that different class loaders can change some of the rules stated so far.



From another perspective, for those who may be confused, if the following prints true, you can ignore what Jim is saying for now:
System.out.println(ClassLoader.getSystemClassLoader() == TextSamplerDemo.class.getClassLoader());
[Tony]: if the following prints true, you can ignore what Jim is saying for now

That is, ignore my last paragraph, the part Tony quoted. Keep the stuff before that.
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards


This thread has been viewed 1228 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jan 21, 2018 19:34:22.