当用户在我的应用程序中单击“帮助”时,我希望能够打开 PDF 文件。PDF 文件位于 JAR 中,解压到 tmp 目录,然后通过 awt.Desktop.getDesktop() 选择打开(以允许 windows 和 linux 使用)。
当我从 Eclipse 运行应用程序时,它工作正常,PDF 打开时没有错误。当我导出到 JAR 并运行时,如果我手动导航到 PDF 文档(在我的 ubuntu 机器 /tmp/546434564.pdf 上),我会收到一条错误消息,指出“PDF 文档已损坏”,然后我在尝试时遇到同样的错误打开文件。我很困惑发生了什么。“损坏”的 PDF 文件大小与工作文件大小相同,因此我认为这不是权限问题。
我正在使用的代码是:
public Main() throws FontFormatException, IOException {
//lets load the font
Font font = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("/Coalition_v2.ttf")).deriveFont(Font.PLAIN, 14);
System.out.println(font);
//lets write the tmp file for help to the machine now
try {
java.io.InputStream iss = getClass().getResourceAsStream("/nullpdf.pdf"); //update the filename here when the help guide is written
byte[] data = new byte[iss.available()];
iss.read(data);
iss.close();
String tempFile = "file";
File temp = File.createTempFile(tempFile, ".pdf");
FileOutputStream fos = new FileOutputStream(temp);
fos.write(data);
fos.flush();
fos.close();
tmphelpfile = temp.getAbsolutePath();
System.out.println(tmphelpfile);
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("TEMP FILE NOT CREATED - ERROR in tmp file writing");
}
然后调用pdf:
JMenu mnHelpGuide = new JMenu("Help Guide");
mnHelpGuide.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// Help();
Desktop d = java.awt.Desktop.getDesktop ();
try {
System.out.println(tmphelpfile);
d.open (new java.io.File (String.valueOf(tmphelpfile)));
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println("Couldnt open your file - error on HELP Guide");
e1.printStackTrace();
}
}
});