尝试使用 Runtime.getRuntime().exec() 执行 Java jar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16302309/
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-10-31 22:33:44  来源:igfitidea点击:

Trying to execute a Java jar with Runtime.getRuntime().exec()

javaprocessruntime.exec

提问by Envin

In the project I am working on, I need to execute a script that I have in a resources folder -- in the class path. I am simply testing the final script functionality, since I am on Windows, I needed a way to output a file to STDIN so I created a simple cat.jar program to clone unixs cat command.

在我正在处理的项目中,我需要执行我在资源文件夹中的脚本——在类路径中。我只是在测试最终的脚本功能,因为我在 Windows 上,我需要一种将文件输出到 STDIN 的方法,所以我创建了一个简单的 cat.jar 程序来克隆 unixs cat 命令。

So when I do "java -jar cat.jar someFile.txt" it will output the file to stdout. I'm sure there are different ways of doing what I did.

因此,当我执行“java -jar cat.jar someFile.txt”时,它会将文件输出到标准输出。我确信有不同的方式来做我所做的事情。

Anyways, I want to run that JAR from my main java program. I am doing

无论如何,我想从我的主 Java 程序运行该 JAR。我在做

Runtime.getRuntime().exec("java -jar C:/cat.jar C:/test.txt");

I've tried switching the forward slash to a backward slash and escaping it -- didn't work. Nothing is getting sent to standard out.

我试过将正斜杠切换为反斜杠并转义它 - 没有用。没有任何东西被发送到标准输出。

Where as, if I run the cat jar on its own, I get the file directed to standard out.

如果我自己运行 cat jar,我会将文件定向到标准输出。

What am I doing wrong here? Is this enough information?

我在这里做错了什么?这是足够的信息吗?

采纳答案by Ravi Thapliyal

Use the Processinstance returned by exec()

使用Process返回的实例exec()

Process cat = Runtime.getRuntime().exec("java -jar C:/cat.jar C:/test.txt");
BufferedInputStream catOutput= new BufferedInputStream(cat.getInputStream());
int read = 0;
byte[] output = new byte[1024];
while ((read = catOutput.read(output)) != -1) {
    System.out.println(output[read]);
}


References:
http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html


参考资料:http:
//docs.oracle.com/javase/7/docs/api/java/lang/Process.html

By default, the created subprocess does not have its own terminal or console. All its standard I/O (stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream().

默认情况下,创建的子进程没有自己的终端或控制台。它的所有标准 I/O(stdin、stdout、stderr)操作都将被重定向到父进程,在那里可以通过使用 getOutputStream()、getInputStream() 和 getErrorStream() 方法获得的流访问它们。

http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#getInputStream()

http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#getInputStream()

getInputStream() returns the input stream connected to the normal output of the subprocess.

getInputStream() 返回连接到子进程正常输出的输入流。