如何从另一个java程序中运行.jar文件?

如何从另一个java程序中运行.jar文件?

问题描述:

我有一个.jar文件,我可以在命令行上运行:

i have a .jar file, which I can run on the command line:

java -jar myFile.jar argument1

我想将此.jar的输出保存为另一个java程序中的String变量。

I want to save the output of this .jar as a String variable inside another java program.

我该怎么做?

我尝试在我的程序中包含myFile.jar作为参考,然后执行 myFile.main(new String {argument1})。但这只是将结果打印到控制台,我无法在我的程序中使用结果。

I tried including myFile.jar as a reference in my program, and doing myFile.main(new String{"argument1"}) in my program. But this just prints the results to console, I can't use the results in my program.

希望这不会太混乱。

如果你不能包括其他jar,

If you can't include the other jar,

你可以使用类似的东西

Runtime re = Runtime.getRuntime();
BufferedReader output;          
try{ 
  cmd = re.exec("java -jar MyFile.jar" + argument); 
  output =  new BufferedReader(new InputStreamReader(cmd.getInputStream()));
} catch (IOException ioe){
  ioe.printStackTrace();
}
String resultOutput = output.readLine();

我知道我的代码不像捕捉异常等完美,但我认为这可以给你一个好主意。

I know my code isn't perfect like the catching exception, etc but I think this could give you a good idea.