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

随声附和 提交于 2019-12-18 07:04:58

问题


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.

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.

Anyways, I want to run that JAR from my main java program. 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?


回答1:


Use the Process instance returned by 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

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().

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.



来源:https://stackoverflow.com/questions/16302309/trying-to-execute-a-java-jar-with-runtime-getruntime-exec

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