[英]Java unable to open pdf using Runtime
我必须在单击 JMenuItem 时打开 pdf。 如果我从 netbeans 运行我的程序,我可以在单击菜单项时打开 pdf。 但是当我从 jar 文件运行时,它没有打开。 我清理并构建我的项目。 但没有变化。 从 netbeans 运行但不从 jar 文件运行时运行。 我需要添加一些库吗?
我的代码如下
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
//System.out.println(Menubar1.getDefaultLocale());
URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
System.out.println(link2);
String link3="F:/new/build/classes/newpkg/Documentation.pdf";
try {
Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link2);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
也试过这个但得到同样的东西..当我从 netbeans 但不能从 jar 应用程序运行时,我可以从 menuitem 打开 pdf。
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
File file=new File(link);
System.out.println(file);
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
对于第二个代码,从 netbeans 运行时,所有 system.out.println() 的 output 如下所示
run:
F:/new/build/classes/newpkg/Documentation.pdf F:\new\build\classes\newpkg\Documentation.pdf 构建成功(总时间:5 秒)
rundll32.exe
无法处理现在位于 Jar 内的资源。 检查getResource(String)
返回的 URL 。
..但仍然无法正常工作..
问题在于,至少对于 PDF, rundll32
仅适用于File
实例。 使用(例如显示)PDF 的工具通常不是为接受命令行参数而设计的。 代表URL
。 如果URL
应该指向File
,则该过程可以继续。 但是一旦 PDF 在 Jar 中,它就只是 Jar 中的一个条目。 或者换句话说,它不是File
。
如果该推理是正确的,在默认软件中显示 PDF 的一种方法是:
URL
。URL
指向 Jar(它将包含“.”)。 如果是这样..
File
。File
。 能用Java 6和Desktop
API吗?
在启动时,您可以将文件导出或下载到磁盘吗?
try //try statement
{
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "c:\\chart.pdf"); //open the file chart.pdf
} catch (Exception e) //catch any exceptions here
{
System.out.println("Error" + e ); //print the error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.