2

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?

4

1 回答 1

2

使用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]);
}


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

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

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

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

于 2013-04-30T15:18:51.573 回答