justik
justik

Reputation: 4255

Java, display chm file loaded from resources in jar

I am trying to display the chm file containing the help which is loaded from resources:

try  
{
    URL url = this.getClass().getResource("/resources/help.chm");

    File file = new File(url.toURI());
    Desktop.getDesktop().open(file);       //Exception 
} 

catch (Exception e) 
{
     e.printStackTrace();
}

When the project is run from NetBeans, the help file is displayed correctly. Unfortunately, it does not work, when the program is run from the jar file; it leads to an exception.

In my opinion, the internal structure of jar described by URI has not been recognized... Is there any better way? For example, using the BufferReader class?

BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream()));

An analogous problem with the jpg file has been fixed with the BufferedImage class

BufferedImage img = null;
URL url = this.getClass().getResource("/resources/test.jpg");
if (url!= null)
{
     img = ImageIO.read(url);
}

without any conversion to URI...

Thanks for your help...

Upvotes: 1

Views: 354

Answers (1)

VGR
VGR

Reputation: 44292

A .jar file is a zip file with a different extension. An entry in a .jar file is not itself a file, and trying to create a File object from a .jar resource URL will never work. Use getResourceAsStream and copy the stream to a temporary file:

Path chmPath = Files.createTempFile(null, ".chm");

try (InputStream chmResource =
    getClass().getResourceAsStream("/resources/help.chm")) {

    Files.copy(chmResource, chmPath,
        StandardCopyOption.REPLACE_EXISTING);
}

Desktop.getDesktop().open(chmPath.toFile());

As an alternative, depending on how simple your help content is, you could just store it as a single HTML file, and pass the resource URL to a non-editable JEditorPane. If you want to have a table of contents, an index, and searching, you might want to consider learning how to use JavaHelp.

Upvotes: 2

Related Questions