javaeclipseswingpdfclown

executable jar from eclipse unable to use images within packages... sometimes


I have wrote a swing application and it works fine in eclipse but when I export it as a runnable jar parts of the application fail, when dealing with images, this line for example;

logo = getClass().getResource("/com/cogentautomation/logo.jpg").getPath();

eclipse is packaging the images in the com.cogentautomation package and I can see it in the .jar itself, I have tried both export methods, extract required libraries and package required libraries, one says;

FileNotFoundException com\cogentautomation\logo.jpg

the other says;

FileNotFoundException file:\c:\documents\hs.jar!\com\cogentautomation\logo.jpg

I am using a library to parse out a PDF file, which is where this error is occurring, however it works in eclipse and with other images that are on disk that aren't a java resource.

I've read other topics on the problem but nothing really seemed to help.

EDIT: addressing something in the comments, I require a String variable the library I am using requires a string input to read the image;

import org.pdfclown.documents.contents.entities.Image;

Image image = Image.get(logo);

Solution

  • Based on the JavaDocs for org.pdfclown.documents.contents.entities.Image I "guess" the Image.get(String) is forwarding the call to Image.get(File) using the String as the parameter for the constructor of File

    This isn't going to work for URL based paths. Instead, you need to look towards Image.get(IInputStream) (why these APIs can't simply use what's already available :P)

    So, digging through the API some more IInputStream leads to org.pdfclown.bytes.Buffer, not perfect, but it's a link.

    You can use Class#getStreamAsResource and write this into a ByteArrayOutputStream which can then give you a byte[], which can then pass to Image.get(IInputStream)