问题
What I'm basically trying to do here, is run a .jar file which is located under
C/Users/-any user here-/appdata/Roaming/-my folder here-/-file name here-.jar
Do I somehow open a CMD and do:
cd appdata/Roaming/<Folder>
java -jar <FileName>.jar
This seems to work when I type it into CMD itself. I can't seem to make it work when running from java program.
I tried to do:
Runtime.getRuntime().exec("cd appdata/Roaming");
And I get an error that the specified directory doesn't exist.
回答1:
Use an absolute path instead of a relative path, that should prevent the path not being found if you run from any working directory. Otherwise add it to your classpath as Nizil said.
To get the current user's name, use System.getProperty("user.name") and concatenate into your path.
user = System.getProperty("user.name");
cmd = "java -jar C/Users/" + user + "/appdata/Roaming/<folder>/<file>.jar";
Runtime.getRuntime().exec(cmd);
回答2:
You just have to add the jar's path in your classpath (don't forget to use an absolute path), and call the main method of the jar in you code. However, this solution is user-specific, as the path will be harcoded, unless you want to dive into something more tricky (How do you change the classpath within java).
来源:https://stackoverflow.com/questions/17693540/how-to-run-a-jar-file-from-within-java-program