问题:在 Windows 平台上本地运行时,Java 小程序无法加载位于其 jar 内的资源。如果同一个小程序是从 Web 服务器启动而不是本地启动,或者是在 Linux 系统上本地启动,则它可以加载资源。在所有情况下,小程序都是使用小程序标签启动的。
重现步骤
1) 构建下面的小程序类代码并创建一个包含以下内容的 jar:
- TestApplet.class
- iconimg.png
- test.html
- META-INF folder (standard manifest with one line: "Manifest-Version: 1.0")
这是我使用的图像 png 文件的链接: http://flexibleretirementplanner.com/java/java-test/iconimg.png
文件 test.html 有一行:
<h1>Text from test.html file</h1>
2) 在与 test.jar 相同的文件夹中创建 launch.html,如下所示:
<html><center><title>Test Applet</title><applet
archive = "test.jar"
code = "TestApplet.class"
name = "Test Applet"
width = "250"
height = "150"
hspace = "0"
vspace = "0"
align = "middle"
mayscript = "true"
></applet></center></html>
3) 将 test.jar 与 launch.html 放在同一本地文件夹中,单击 launch.html
4) 请注意,getResource() 调用 imgicon.png 和 test.html 均返回 null。
5) 将 launch.html 和 test.jar 上传到 Web 服务器并加载 launch.html,您会发现资源已找到。
TestApplet.java
import java.applet.AppletContext;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestApplet extends JApplet {
public TestApplet() {
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void init() {
JPanel topPanel = new JPanel();
JLabel iconLabel;
URL url = TestApplet.class.getClassLoader().getResource("iconimg.png");
if (url != null)
iconLabel = new JLabel(new ImageIcon(url));
else
iconLabel = new JLabel("getResource(iconimg.png)==null");
topPanel.add(iconLabel);
URL url2;
url2 = TestApplet.class.getClassLoader().getResource("test.html");
if (url2 == null) {
JLabel errorLabel = new JLabel("getResource(test.html) == null");
topPanel.add(errorLabel);
} else {
try {
JEditorPane htmlPane = new JEditorPane(url2);
topPanel.add(htmlPane);
} catch (IOException ioe) {
System.err.println("Error displaying " + url2);
}
}
getContentPane().add(topPanel);
}
private void jbInit() throws Exception { }
}
最佳答案
由于安全原因,自 Windows 1.7.0_25 起,Oracle 已决定修改 getDocumentBase()、getCodeBase() 和 getResource() 的行为:http://www.duckware.com/tech/java-security-clusterfuck.html
似乎有很多关于此更改的讨论,因为它破坏了一些重要的有效且安全的用例。
关于Java小程序在本地运行找不到jar中的资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17572293/