我希望能够打开一个PDF文件时,用户点击'帮助'在我的应用程序。PDF文件位于JAR中,解压缩到tmp目录,然后通过awt.Desktop.getDesktop()选择打开(允许windows和linux使用)。
当我从Eclipse中运行应用程序时,它工作正常,PDF打开时没有错误。当我导出到JAR并运行时,我会得到一个错误,说明"PDF文档损坏",如果我手动导航到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();
}
}
});
谢谢大家的帮助。通过导入apachecommago jar,然后将代码修改为:
,可以解决这个问题: 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()];
byte[] data = IOUtils.toByteArray(iss);
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");
}