How to run a .jar file from within Java program?

别等时光非礼了梦想. 提交于 2019-12-08 09:15:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!