访问 Jar 中的 PDF
我正在使用 Netbeans 创建 Java 应用程序。我需要从“帮助”菜单项中打开一个 PDF 文件。当我通过 Netbeans 运行应用程序时,文档会打开,但通过 jar 文件打开时,它不会打开。有什么可以做的吗?
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
URL link2=getClass().getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
System.out.println(link2);
String link3="E:/new/build/classes/newpkg/Documentation.pdf";
try {
Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link3);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
两个输出如下:
E:/new/build/classes/newpkg/Documentation.pdf
file:/E:/new/build/classes/newpkg/Documentation.pdf
考虑上面的代码片段。在打印“link”时,我们可以看到它与硬编码的“link3”完全相同。使用硬编码的 'link3' 时,PDF 文件从 jar 应用程序中打开。但是,当我们使用链接时,尽管它与“link3”完全相同,但 PDF 无法打开。
I'm creating a Java application using Netbeans. From the 'Help' Menu item, I'm required to open a PDF file. When I run the application via Netbeans, the document opens, but on opening via the jar file, it isn't opening. Is there anything that can be done?
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
URL link2=getClass().getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
System.out.println(link2);
String link3="E:/new/build/classes/newpkg/Documentation.pdf";
try {
Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link3);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
The two outputs are as follows:
E:/new/build/classes/newpkg/Documentation.pdf
file:/E:/new/build/classes/newpkg/Documentation.pdf
Consider the above code snippet. On printing 'link',we can see that it is exactly same as the hard coded 'link3'. On using the hard coded 'link3' , the PDF file gets opened from jar application. But when we use link, though it is exactly same as 'link3', the PDF doesn't open.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这很可能与 PDF 资源加载不正确有关。在 IDE 中,您可以将 PDF 文件作为项目结构的一部分或直接指定相对路径。当打包的应用程序运行时,它看不到资源。
编辑:
正如我所描述的,您的代码揭示了问题。可以使用以下方法来正确识别资源路径。
请参阅这个问题,它可能会提供更多信息。
This is most likely related to the incorrect PDF resource loading. In the IDE you have the PDF file either as part of the project structure or with a directly specified relative path. When a packaged application is running it does not see the resource.
EDIT:
Your code reveals the problem as I have described. The following method could be used to properly identify resource path.
Pls refer to this question, which might provide additional information.
试试这个:
Try out this: