0
votes

I have a Calculator.jar file that I created with Netbeans.

I want to run that jar file using java code. After looking around stackoverflow and some documentation sites, I tried the following:

public static void main (String [] args){
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("java -jar C:\\pathToJar\\Calculator.jar);
    pr.waitFor();
}

The code runs fine, but my problem comes in with the path to the file. If I run the program without the absolute path, it runs and finishes, but I never see the calculator GUI pop up. When I run with the absolute path, the GUI pops up as expected.

I have the jar file in the same place as my source code. I thought doing that would allow me to just have to put Calculator.jar without the absolute path. That doesn't seem to work though.

Does anyone know how I could possibly store the jar file so I don't need to use the absolute path?

Edit: I also tried creating a separate package within the project called jarFiles and tried the path jarFiles\Calculator.jar. That didn't work either. I think I'm misunderstanding something about the default path/what path cmd is using by default when I call the command. I'm not sure though.

Thanks for any advice in advance!

1
The "current working directory" is whatever directory you change into just before running the program. In some IDEs, it may be set to a specific point relative to the class files. But you can't rely on this when you write a program. Either resolve the path relative to a known point, or use an absolute path. - RealSkeptic
But if I write something like "projectpackage\src\Calculator.jar" that doesn't work. And I'm technically setting a relative path at that point. Or, do I need to do something like, "getWorkingDirectory" and then access the file? - JustBlossom
You might find it educational to see what the current working directory is when you run the program from an IDE. Just remember that when it is run from command line, the users can set any working directory they like. You might want to pass the path as a parameter, an environment variable, or resolve it relative to a known file. - RealSkeptic

1 Answers

0
votes

I believe the problem that you're having is that when you try

public static void main (String [] args){
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("java -jar \\Calculator.jar");
    pr.waitFor();
}

It looks into the root directory of the computer, also, there was a quotation mark forgotten on the end. The way you should access the current working directory is by simply eliminating the \\, you might also want to surround the jar file path in quotation marks, just in case.

public static void main (String [] args){
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("java -jar \"Calculator.jar\"");
    pr.waitFor();
}