Search code examples
javanetbeansjarprocessbuilder

Running .JAR file from java code (netbeans)


Im trying to run a jar file from java code, But unfortunately does not success. A few details about the jar file:

  1. The jar file located in a different folder (For example - "Folder").
  2. The jar file using a files and folders are in the root folder (the same "Folder" i mentioned above).

What im trying to do so far:

JAR file project.

  1. In netbeans i checked that the main class are defiend (Project properties -> Run -> Main Class).

Other JAVA program

  1. Trying to run with the command:

      Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar");
    

    &&

      Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar" "C:\\Software");
    

    The jar file opened well, But he doesnt know and recognize his inner folders and files (the same "Folder" i mention above). In short, it does not recognize its root folder.

  2. Trying to run with ProcessBuilder

           ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "start", "javaw", "-jar", "C:\\Software\\program.jar");
        pb.directory(new File("C:\\Software"));
        try {
            pb.start();
        } catch (IOException ex) {
    
        }
    

In Some PC's its works fine, But in other pc's its not work and i got an error message: "Could not find the main class" ** Offcourse if i run the jar with double click its works.

So how can i run a jar file from other java program ?


Solution

  • Use this variant of .exec where you specify working folder as the third argument. (In your examples, you always only use one argument.)

    exec("javaw -jar "C:\\Software\\program.jar", null, "C:\\Software");