Idon89
Idon89

Reputation: 141

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 ?

Upvotes: 0

Views: 1213

Answers (2)

kemparaj565
kemparaj565

Reputation: 385

You can try to call it something like below. There are 2 types of calling it.

public class JarExecutor {

public static void main(String[] args) throws IOException, InterruptedException {

//This is first way of calling.

Process proc=Runtime.getRuntime().exec(new String[]{"java","-jar" ,"C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar"});

//This is second way of calling.

    Process proc=Runtime.getRuntime().exec(new String[]{"java","-cp","C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar","com.shiva.practise.FloydTriangle"});
    proc.waitFor();
    BufferedInputStream is=new BufferedInputStream(proc.getInputStream());
    byte[] byt=new byte[is.available()];
    is.read(byt,0,byt.length);
    System.out.println(new String(byt));

}

}

Upvotes: 0

Stefan
Stefan

Reputation: 2385

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

Upvotes: 1

Related Questions