如何从 Java 程序中运行 .jar 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17693540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:42:22  来源:igfitidea点击:

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

javaprocesscmdcommandruntime.exec

提问by user2098268

What I'm basically trying to do here, is run a .jar file which is located under

我在这里基本上要做的是运行一个 .jar 文件,它位于

C/Users/-any user here-/appdata/Roaming/-my folder here-/-file name here-.jar

Do I somehow open a CMD and do:

我是否以某种方式打开 CMD 并执行以下操作:

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.

当我将它输入到 CMD 本身时,这似乎有效。从 java 程序运行时,我似乎无法使其工作。

I tried to do:

我试图做:

Runtime.getRuntime().exec("cd appdata/Roaming");

And I get an error that the specified directory doesn't exist.

我收到一个错误,指出指定的目录不存在。

回答by CrystalDuck

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.

使用绝对路径而不是相对路径,这样可以防止在从任何工作目录运行时找不到路径。否则,如 Nizil 所说,将其添加到您的类路径中。

To get the current user's name, use System.getProperty("user.name")and concatenate into your path.

要获取当前用户的名称,请使用System.getProperty("user.name")并连接到您的路径中。

user = System.getProperty("user.name");
cmd = "java -jar C/Users/" + user + "/appdata/Roaming/<folder>/<file>.jar";
Runtime.getRuntime().exec(cmd);

回答by NiziL

You just have to add the jar's path in your classpath (don't forget to use an absolute path), and call the mainmethod 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).

你只需要在你的类路径中添加 jar 的路径(不要忘记使用绝对路径),并main在你的代码中调用jar的方法。但是,此解决方案是特定于用户的,因为路径将被硬编码,除非您想深入研究更棘手的内容(如何更改 java 中的类路径)。