Loading images from jar files in windows
In the first version of the server app, I was telling Windows users to start the program by clicking on a .bat file because for some reason, the thing wasn’t starting up when clicking on the .jar file directly.
I’d seen other apps that did start from the jar file just fine, and after a lot of hunting around, I figured out why. When you search google for load image from jar file, most of the hits have you getting a URL object like this:
URL url = this.getClass().getResource("the_image.jpg");
then using that to load the actual image.
This works just fine on OSX, and Linux, but does absolutely nothing on Windows for some reason. Instead, on Windows, you have to get a JarFile object for the jar you’re loading from, then get a ZipEntry (JarEntry, whatever) from that, then get an InputStream from the ZipEntry, turn that into a BufferedInputStream, then pass that off to your default Toolkit to turn into an image.
Of course this means you have to figure out whether the app’s being run in a jar file in the first place or not. This is how I’m doing it:
URL fileURL = this.getClass().getProtectionDomain().getCodeSource().getLocation(); String sBase = fileURL.toString(); if ("jar".equals(sBase.substring(sBase.length()-3, sBase.length()))) { MyClass.jar = new JarFile(new File(fileURL.toURI())); }
after that, you can load the image ike this:
Image imReturn = null; try { if (jar == null) { // This is used if you're not loading from a jar imReturn = this.toolkit.createImage(this.getClass().getClassLoader().getResource(sImage)); } else { // BufferedInputStream bis = new BufferedInputStream(jar.getInputStream(jar.getEntry(sImage))); ByteArrayOutputStream buffer=new ByteArrayOutputStream(4096); int b; while((b=bis.read())!=-1) { buffer.write(b); } byte[] imageBuffer=buffer.toByteArray(); imReturn = this.toolkit.createImage(imageBuffer); bis.close(); buffer.close(); } } catch (IOException ex) { } return imReturn;