Why would he create a separate thread for a question that is relevant to this thread?..
Didn’t he say that his code could only work with Eclipse?
No, I helped him fix his issue so his code also works when exported. He was just wondering why specifically his code only used to work when in Eclipse.
For the record, the “standard” way of loading things that will be packaged in a jar file (the same jar file as your code) is [icode]Whatever.class.getResourceAsStream(“fileName”);[/icode] The URL method also works, but is easier to screw up, as URLs are quite finicky about their paths.
fileName is relative to the project directory, usually. (If you start messing with runtime parameters, you can change the working directory and change this kind of stuff)
File handling is a common problem for newbies or those who simply haven’t done it much because they get it working in eclipse, but then it doesn’t work when exported, and they don’t know what to do.
It works “in eclipse” because in that environment the file actually exists, when exported it doesn’t exist as a file, it’s an entry in a jar file (which is a actually a zip file), so methods expecting a resource as it’s own file will break. getResourceAsStream() calls ClassLoader.getResourceAsStream() under the hood, and the classloader can load these entries because it is aware of the jar file environment. You can actually write your own code that will do the same, but it’s easier and much more robust to simply use Class.getResourceAsStream().
You’re one of today’s 10,000! I hope you learned something useful about file handling in Java.
Err, [icode]SomeClass.class.getResourceAsStream(path)[/icode] denotes a path relative to the package of SomeClass, unless the path starts with a slash, in which case it is relative to the root of the classloader of SomeClass.
[icode]SomeClass.class.getClassLoader().getResourceAsStream(path)[/icode] denotes a path relative to the root of the classloader.
In the opening post, the problem is that the images are in the same package as the class, but because he added .getClassLoader(). the images are not searched for in the class’s package, but in the root of the classloader. Why it worked in Eclipse? Probably because he added the package as an entry to the classpath.
Well damn, that’s embarrassing, you are quite right. I looked back at some code that I wrote a while ago which I was reminded of by this thread, turns out the class was in the default “package,” confusing the issue.
Classpath issues confuse even experts, because ‘we’ put such callsites behind an abstraction layer or two, after which only a vague memory of their inner workings remains…
Hence my recent exploration and adoration of the nio Files and Paths classes. Turns most common IO tasks into one-liners without having to force your brain to internalize a new system of those “inner workings.”
Maybe I should use Guava.
Edit: Moar abstraction! I’m already numb!