【发布时间】:2021-05-03 20:54:45
【问题描述】:
我有一个 JEditorPane,它显示带有图像的 HTML 内容。 我找到了这篇文章:JEditorPane with inline image。 在本文中提到使用协议处理程序“resource:”作为类路径资源。
当我从 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。
有趣的是,当我用resourceURL 创建一个ImageIcon 时,图像被加载(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: 开头。
【问题讨论】:
标签: java html swing jeditorpane