我正在尝试使用我的应用程序打开位于ressource文件夹中的pdf。 它在模拟器上工作,但是当我尝试导出的应用程序时没有任何反应。 我猜我没有使用rigth路径但是没有看到我错在哪里。 getRessource方法适用于我的图像。
以下是代码段:
public void openPdf(String pdf){
if (Desktop.isDesktopSupported()) {
try {
URL monUrl = this.getClass().getResource(pdf);
File myFile = new File(monUrl.toURI());
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我指的是pdf变量:“name_of_the_file.pdf”
编辑:我已经粘贴了整个方法
答案 0 :(得分:5)
好的,解决了。该文件位于Jar中,获取它的唯一方法是通过输入队/输出并创建临时文件。
这是我的最终代码,效果很好:
public void openPdf(String pdf){
if (Desktop.isDesktopSupported())
{
InputStream jarPdf = getClass().getClassLoader().getResourceAsStream(pdf);
try {
File pdfTemp = new File("52502HPA3_ELECTRA_PLUS_Fra.pdf");
// Extraction du PDF qui se situe dans l'archive
FileOutputStream fos = new FileOutputStream(pdfTemp);
while (jarPdf.available() > 0) {
fos.write(jarPdf.read());
} // while (pdfInJar.available() > 0)
fos.close();
// Ouverture du PDF
Desktop.getDesktop().open(pdfTemp);
} // try
catch (IOException e) {
System.out.println("erreur : " + e);
} // catch (IOException e)
}
}
答案 1 :(得分:1)
您提到它在模拟器上运行但在应用程序上没有运行。运行应用程序的平台很可能不支持Desktop
。
Desktop.isDesktopSupported()
可能会返回false
。因此没有堆栈跟踪或任何东西。
在Mac上,你可以这样做:
Runtime runtime = Runtime.getRuntime();
try {
String[] args = {"open", "/path/to/pdfFile"};
Process process = runtime.exec(args);
} catch (Exception e) {
Logger.getLogger(NoJavaController.class.getName()).log(Level.SEVERE, "", e);
}