1
votes

i have a jar file called bg.jar which prints some numbers. i want to call this bg.jar from a java program. i used this code

public class bg1 {
public static void main(String[] args) {
    try{
     //  Process ps = Runtime.getRuntime().exec("java -jar bg.jar");
      ProcessBuilder builder = new ProcessBuilder("java -jar bg.jar");
      Process process = builder.start();

    }catch(Exception e){
        System.out.println("e: "+ e.toString());
    }
  }
}

i added bg.jar in the libraries folder of bg1 project. but when i run bg1.class it gives me this error:

e: java.io.IOException: Cannot run program "java -jar bg.jar": CreateProcess error=2, The system cannot find the file specified

how can i call bg.jar from bg1.class

2
Can you try moving bg.jar to src folder ? - Rakesh
@Rakesh i tried it.. gives me the same error - anonymous
can you print the full stacktrace - e.printStackTrace() instead of e.toString() ? - Rakesh
@Rakesh no its not throwable, so it is not allowing me to print e.printStackTrace() - anonymous
remove the SOP line and replace it with just e.printStackTrace(); - Rakesh

2 Answers

1
votes

I think the file not found error is that the system cannot find the "java" executable file. One way is to add the "java" directory path to the environment variable PATH. To find the variable, right click on the "My Computer"/Advanced system settings/Environment Variables/System variables. Then open a new console, run your Java program above.

Alternative way is probably to load the jar file to your Java program. And then run the static main method in your Java codes. To dynamically load java files, see How to load a jar file at runtime. The class that contains the main method can be found by parsing the META-INF/MANIFEST.MF file in the jar file.

0
votes

ProcessBuilder builder = new ProcessBuilder("java -jar bg.jar");

Space does not work in process builder command, I tried using comma separated words, and it worked.

Something like this for command "make macosx"-

ProcessBuilder builder = new ProcessBuilder("make" , "macosx");