This problem has been bugging me for a while. I have to load a couple files in my java app, and the only way I got working so far looks like this:
URL hsURL;
if(System.getProperty("os.name").toLowerCase().contains("windows")) {
hsURL = new URL("file:/" + System.getProperty("user.dir") + "/helpsets/helpset.hs");
}
else {
hsURL = new URL("file://" + System.getProperty("user.dir") + "/helpsets/helpset.hs");
}
But this is ugly and terrible. For a while I thought I had this working:
hsURL = ClassLoader.getSystemResource("helpsets/helpset.hs");
But that no longer works for some reason (I must have changed something and not noticed. It returns null.
Should I be using getResource() instead of getSystemResource() (if so, why is getSystemResource() static but not getResource())?
I am using eclipse and I have tried including the folder in the build path (classpath) and not including it, it doesn’t seem to make a difference.
getSystemResourceis static because it will use the system classloader, which is available statically. (ClassLoader.getSystemClassLoader)If your resource is available in the classpath, I would suggest using
ClassLoader.getResource()orClass.getResourcefrom an appropriate class, e.g.(
ClassLoader.getResourceis “absolute”;Class.getResourceis relative to the package of the class unless you prefix it with a ‘/’.)If this doesn’t work, please post how your app is configured in terms of the classpath, and where your file is.
EDIT: I usually find the URL less useful than an
InputStream, so I usegetResourceAsStreaminstead ofgetResource. YMMV