简体   繁体   English

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

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

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. 因此,当我执行“ java -jar cat.jar someFile.txt”时,它将输出文件到stdout。 I'm sure there are different ways of doing what I did. 我敢肯定,我做的事情有不同的方式。

Anyways, I want to run that JAR from my main java program. 无论如何,我想从主Java程序运行该JAR。 I am doing 我在做

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. 在哪里,如果我自己运行猫罐,我会将文件定向到标准输出。

What am I doing wrong here? 我在这里做错了什么? Is this enough information? 这是足够的信息吗?

Use the Process instance returned by exec() 使用exec()返回的Process实例

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()返回连接到子流程正常输出的输入流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM