MademoiselleLenore
MademoiselleLenore

Reputation: 569

open pdf file located in a ressource folder

I'm trying to open a pdf located in a ressource folder with my application. It does work on the emulator but nothing happens when I try on the exported application. I'm guessing I'm not using the rigth path but do not see where I'm wrong. The getRessource method works very well with my images.

Here is a code snippet :

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

I'm referring to the pdf variable this way : "name_of_the_file.pdf"

Edit: I've pasted the whole method

Upvotes: 2

Views: 4688

Answers (2)

MademoiselleLenore
MademoiselleLenore

Reputation: 569

Ok, solved it. The file being located in a Jar, the only way to get it was through a inputsteam/outstream and creating a temp file.

Here is my final code, which works great :

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

Upvotes: 5

Jatin
Jatin

Reputation: 31754

You mentioned that it is running on Emulator but not on the application. There is high probability that the platform on which the application is running does not support Desktop.

Desktop.isDesktopSupported()

might be returning false. Hence no stack trace or anything.

On Mac, you can do:

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

Upvotes: 1

Related Questions