Java,显示从jar中的资源加载的chm文件

问题描述:

我正在尝试显示包含从资源加载的帮助的 chm 文件:

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();
}

当项目从 NetBeans 运行时,帮助文件正确显示.不幸的是,当程序从 jar 文件运行时,它不起作用;它导致异常.

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.

在我看来,URI描述的jar内部结构没有被识别...有没有更好的方法?例如,使用 BufferReader 类?

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()));

已使用 BufferedImage 类修复了 jpg 文件的类似问题

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);
}

无需任何转换为​​ URI...

without any conversion to URI...

感谢您的帮助...

.jar 文件是具有不同扩展名的 zip 文件..jar 文件中的条目本身不是一个文件,并且尝试从 .jar 资源 URL 创建 File 对象将永远无法工作.使用 getResourceAsStream 并将流复制到临时文件:

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());

作为替代方案,根据帮助内容的简单程度,您可以将其存储为单个 HTML 文件,并将资源 URL 传递给不可编辑的 JEditorPane.如果您想拥有目录、索引和搜索,您可能需要考虑学习如何使用 JavaHelp一>.

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.