Java 打开位于ressource文件夹中的pdf文件

Java 打开位于ressource文件夹中的pdf文件,java,executable-jar,Java,Executable Jar,我正在尝试使用我的应用程序打开位于ressource文件夹中的pdf。 它在模拟器上可以工作,但在我尝试导出的应用程序时没有发生任何事情。 我猜我没有使用rigth路径,但看不出我错在哪里。getRessource方法可以很好地处理我的图像 以下是一段代码片段: public void openPdf(String pdf){ if (Desktop.isDesktopSupported()) { try { URL monUrl = this.

我正在尝试使用我的应用程序打开位于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”


编辑:我已经粘贴了整个方法

您提到它是在Emulator上运行的,但不是在应用程序上。运行应用程序的平台很可能不支持
桌面

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);
    }

好的,解决了。文件位于Jar中,获取它的唯一方法是通过inputsteam/outstream并创建临时文件

以下是我的最终代码,非常有效:

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)
        }
    }

请同时显示异常处理部分…嗯,空的catch块…我已经测试了异常,而不是问题。是的,我已经用警告消息测试了该部分。当然,最终版本会有不同的处理方式。所以问题不是来自于……如果你使用java 7(或以后),你应该考虑使用试用资源。