0

I am using the following code to open a pdf file from java. The code works when I run the application from the IDE. However, when generating the jar and executing it, the code stops working. I do not know what I'm doing wrong. I have tried changing the jar of folders but it still does not work. It seems that the problem is how ubuntu 16.04 handles the routes because in windows this works correctly. The application does not throw exceptions

The way I get the pdf I do the same for another application but in it I get an image and it works both in the jar and in executing it in the ide.

 jbTree.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/tree.png")));

Structure of the project

Application

Button code

   if (Desktop.isDesktopSupported()) {
        try { 
            File myFile = new File (getClass().getResource("/help/help.pdf").toURI());
            Desktop.getDesktop().open(myFile);
        } catch (IOException | URISyntaxException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

The solution is run the application through the console. Trying to run it in another way does not work.

pete
  • 355
  • 3
  • 14
  • Possible duplicate of [Reading file in java (eclipse IDE used)](https://stackoverflow.com/questions/5612300/reading-file-in-java-eclipse-ide-used) – Robin Green May 06 '18 at 05:54
  • 1
    Is your pdf probably packed into the jar, too? – mkl May 06 '18 at 09:37
  • 1
    @RobinGreen I'm not trying to read a file by lines.I am trying to open a pdf from a button in my application. This works for me in windows. In ubuntu 16.04 it does not work for me. – pete May 07 '18 at 13:13
  • @mkl I think the problem is with the path in windows working properly. But at the moment I am using ubuntu 16.04 and it does not work. – pete May 07 '18 at 13:14
  • 1
    Does Desktop.getDesktop().open(myFile); open any other file? Instead of printing just "Exception", you should print the original stacktrace to see, what the actual message is, "no such file or directory" (possibly a mismatch in upper/lowercase, where Windows is sloppy about), missing permissions (unlikely, but possible) or maybe there is no program specified for the Desktop to open PDFs (don't know where to look for it - maybe settings: default application on Ubuntu level). And see Thecarismas post, how to write a [mcve]. – user unknown May 07 '18 at 13:26
  • Also, does the file exist in the same location on Ubuntu? – Robin Green May 07 '18 at 13:46
  • The file if it exists in the location when I run it in the IDE works fine. However, when I export the jar it does not work no matter what folder I put the jar in. @RobinGreen – pete May 07 '18 at 14:21
  • 1
    The file cannot be read from inside the jar. Have you copied the PDF file onto the Ubuntu system and put it in the same place? Does the directory even exist on the Ubuntu system? – Robin Green May 07 '18 at 14:23
  • 1
    @pete *"I think the problem is with the path in windows working properly. But at the moment I am using ubuntu 16.04 and it does not work."* - No. most likely the problem is that your pdf is packed into the jar, too. If the PDF is in the jar, it is not an independent file in the file system. Your `Desktop.getDesktop().open(myFile)`, on the other hand, does expect an independent file in the file system. – mkl May 07 '18 at 14:51

1 Answers1

2

When you run the project from your IDE then the root of your project is the System.getProperty("user.dir") e.g if it Your project root folder is PDFJar the it will look for the help.pdf in the PDFJar/src/project/help/ folder.

After building your project to jar file the executable jar is build and executed from a dist or bin folder which is now the System.getProperty("user.dir") and the help.pdf will be seeked in the dist/src/project/help/ folder.

You either create the folder /src/project/help/ with help.pdf in it in your dist or bin directory or put your Jar file in your project root

EDITED

You can't access a resources file packed into your JAR archive as file except as input stream, The reason it works from you IDE is because the file exist in the src folder as the executed directory is your project folder. You will need to create the file outside the JAR achive then read the stream into it so you can call Desktop to open it.

package stackoverflow;

import java.awt.Desktop;
import java.awt.HeadlessException;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author thecarisma
 */
public class StackOverflow {

    public void openHelpFile() {
        OutputStream outputStream = null;
        try {
            File outFile = new File("./help.pdf"); 
            outFile.createNewFile(); //create the file with zero byte in same folder as your jar file or a folder that exists
            InputStream in = getClass().getResourceAsStream("/help/help.pdf");
            outputStream = new FileOutputStream(outFile);
            int read = 0;
            //now we write the stream into our created help file
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
            }
            if (outFile.exists()) {
                String path= outFile.getAbsolutePath(); 
                JOptionPane.showMessageDialog(null, path);
                if (Desktop.isDesktopSupported()) {
                    JOptionPane.showMessageDialog(null, "Enter");
                    try { 
                        File myFile = new File (path);
                        Desktop.getDesktop().open(myFile);
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(null, "Exception");
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Error Occur while reading file");
            }
        } catch (HeadlessException | IOException ex) {
            Logger.getLogger(StackOverflow.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                outputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(StackOverflow.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        StackOverflow stackOverFlow = new StackOverflow();
        stackOverFlow.openHelpFile();
        //the bellow example works for file outside the JAR archive
        /**
        String path= new File("help.pdf").getAbsolutePath(); 
        JOptionPane.showMessageDialog(null, path);
        if (Desktop.isDesktopSupported()) {
            JOptionPane.showMessageDialog(null, "Enter");
            try { 
                File myFile = new File (path);
                Desktop.getDesktop().open(myFile);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Exception");
            }
        } **/
    }

}

DETAIL

When your resources file is packed into the JAR archive it cannot be accessed as a file except as a stream of file. The location of the file will be absolute in the JAR archive such as the /help/help.file. If you just want read the content of the resources such as conf, xml, text file or such you can just read it into BufferReader i.e

InputStream in = getClass().getResourceAsStream("/conf/conf.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

else if it a binary file you will need to create a file outside the jar file with 0 byte then read the resources stream from the JAR archive into the created file.

NOTE: You should check if the help file already exist with the same size before reading from the JAR archive to prevent reading multiple time and skip the process to increase you run time. Take note while creating your file as creating a file in a folder that does not exist in JAVA is not possible.

YOU CAN OPEN YOUR .jar FILE WITH AN ARCHIVE MANAGER, TO VIEW IT STRUCTURE

Thecarisma
  • 1,424
  • 18
  • 19
  • try changing the line `src/project/help/help.pdf` to just `./help.pdf` then place the `help.pdf` file in the same folder with the jar file – Thecarisma May 06 '18 at 02:08
  • Your code works fine on my system with the Jar file and pdf in same location – Thecarisma May 06 '18 at 02:44
  • I use ubuntu 16.04 can that be why? – pete May 06 '18 at 02:46
  • it likely so. you should try using the absolute path to the file. you can use `realpath help.pdf` in terminal to get the file absolute path – Thecarisma May 06 '18 at 02:54
  • I will try and tell you – pete May 06 '18 at 03:10
  • 1
    Your program works for me to open "./help.pdf". Maybe pete used a file HELP.PDF which works on windows, but not on linux? – user unknown May 07 '18 at 13:33
  • @Thecarisma I update de question. Maybe with that little bit of extra information it serves as something – pete May 07 '18 at 17:36
  • aw to my correction your help file is packed withing your jar file along with the sources? – Thecarisma May 08 '18 at 14:42
  • if it withing your jar file then you cannot use file to open it, you will have to use stream, i will update my answer with some explanation – Thecarisma May 08 '18 at 14:44
  • @Thecarisma I have to say that the problem was solved by running the application through the console. If I clicked directly on the jar it did not work in any way. Although I must clarify that I should do what you said about moving the src directory to dist or the jar to the root directory. Thanks for your help. – pete May 10 '18 at 12:58