0

I have a Java project,exported as a JAR file (Desktop Application) which generates a HTML file as output. The output html file, needs to read one image file, as the page's logo. The JAR application will be in say X folder. The target html file will be placed dynamically anywhere. How do I make the html,residing in someother location, access the image, inside the JAR file.

In short, how do I determine the path for the below code, for the above scenario.

java.net.URL url = getClass().getResource("image.jpg");
fw.write("<tr><td><b>"+csname+"</b></td><td> <img src = "+url.toString()+"'>/td></tr>");

works fine, when i run in eclipse. But not when exported as JAR The resultant html file,in some other folder has the code

<img src="rsrc:com/demo/dirapitoword/image.jpg">

2 Answers2

1

You just need to read the image as a stream from the classpath, e.g.:

InputStream in = getClass().getResourceAsStream("image.jpg");

and write the stream out as a file to a known place on disk. There are lots of ways to do this, if you're using Java 7 or above, try:

File out = new File("image.jpg");
Files.copy(in, out.toPath());

Then, your src attribute can use the relative location you chose to display this image in the HTML, without having to worry about Jar compatibility in the browser / client.

Community
  • 1
  • 1
declension
  • 4,110
  • 22
  • 25
0

You can find that the jar: URI Scheme exist for .zip containers as described in the Wikipedia here http://en.wikipedia.org/wiki/URI_scheme

The format is:

jar:<url>!/[<entry>]

BUT it is not supported by all browsers (only Firefox actually) as described in this article: https://code.google.com/p/browsersec/wiki/Part1

Even in that case, I think it is not very nice that the output .html can be elsewhere but contains an absolute path to your resources.

I suggest to use the data: URI scheme which allows to embed the image within the HTML page.

There is a question that covers this procedure: How to display Base64 images in HTML?

And in one of the answers, there is an interesting fiddle sample here: http://jsfiddle.net/hpP45/

Community
  • 1
  • 1