带有来自 jar 文件的内嵌图像的 JEditorPane

问题描述

我有一个 JEditorPane,它显示带有图像的 HTML 内容。 我找到了这篇文章:JEditorPane with inline image。 在本文中提到使用协议处理程序“资源:”作为类路径资源。

当我从 Eclipse 运行应用程序时,我尝试了这个并让它工作。 但是当我使用生成的 JAR 文件运行它时,我无法从 JAR 文件中读取图像。

这是我的连接类版本:

public class ResourceConnection extends URLConnection {
    protected ResourceConnection(URL url) {
        super(url);
    }

    @Override
    public void connect() throws IOException {
        connected = true;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        String filename = url.getFile();
        URL resourceURL = ResourceConnection.class.getResource(filename);
        String resourcePath = resourceURL.toString();

        Path path = null;
        if (resourcePath.startsWith("file:")) {
            resourcePath = resourcePath.substring(5);
            path = Paths.get(resourcePath);
        } else if (resourcePath.startsWith("jar:")) {
            // TODO path to image in jar file
        }

        if (path != null) {
          byte[] bytes = Files.readAllBytes(path);
          return new ByteArrayInputStream(bytes);
        } else {
          return null;
        }
    }
}

当我从 Eclipse 运行它时,resourcePath 看起来像 file:/path/to/my/project/bin/path/to/image.png。从此我必须删除 file: 并显示图像。

当我使用 JAR 文件运行它时,resourcePath 看起来像 jar:file:/path/to/the/jarfile.jar!/path/to/image.png。我不知道如何操作路径以便 Files.readAllBytes 可以读取它。我尝试了以下方法:

  • 无需操作
  • 删除了jar:
  • 删除了jar:file:
  • resourceURL 转换为 URI 并将其与 Paths.get 一起使用。这导致了 java.nio.file.FileSystemNotFoundException

有趣的是,当我用 ImageIcon 创建一个 resourceURL 时,图像被加载(getIconWidth()getIconHeight() 返回正确的值)。

编辑

HTML 源代码中的标记看起来像 <img src="resource:/path/to/image.png">

编辑

Andrew Thompson 的回答让我想到了使用 FileInputStream

public InputStream getInputStream() throws IOException {
    try {
        String filename = url.getFile();
        URL resourceURL = ResourceConnection.class.getResource(filename);
        return new FileInputStream(new File(resourceURL.toURI()));
    } catch (FileNotFoundException | URISyntaxException e) {
        e.printStackTrace();
        return null;
    }
}

这在 Eclipse 中再次正常工作,但使用 JAR 文件我得到 java.lang.IllegalArgumentException: URI is not hierarchical。可能是因为 URL 以 jar:file: 开头。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)