使用重定向的stdin和stdout从Java运行外部程序 [英] Running external program with redirected stdin and stdout from Java
问题描述
我正在尝试从Java程序运行外部程序,但我遇到了麻烦。基本上我想做的是:
I'm trying to running an external program from a Java program and I'm having trouble. Basically what I'd like to do would be this:
Runtime.getRuntime().exec("./extprogram <fileIn >fileOut");
但是我发现这不起作用 - Java的表达式需要使用处理
包含输入和输出流以及其他我没有遇到过的事情。
However I've found that that doesn't work - Java apparentls needs to use a Process
with input and output streams and other things which I'm not experienced with.
我看过一些互联网上的例子(其中很多来自SO),似乎没有一种简单的标准方式来做到这一点,对于那些不完全了解正在发生的事情的人来说,可能会非常令人沮丧。
I've looked at a number of examples across the internet (many of which are from SO), and there doesn't seem to be a simple standard way of doing this, which for someone who doesn't fully understand what's going on, can be quite frustrating.
我也无法通过其他人的代码示例来构建我自己的代码,因为通常看起来大多数其他人1.对重定向<$ c $不感兴趣c> stdin ,和2.不一定将 stdout
重定向到文件,而是重定向到 System.out
。
I'm also having trouble trying to build my own code off the examples of other people's code because generally it seems most other people 1. aren't interested in redirecting stdin
, and 2. aren't necessarily redirecting stdout
to a file, but instead to System.out
.
那么,是否有人能够指出我的任何好的简单代码模板的方向来调用外部程序并重定向 stdin
和 stdout
?谢谢。
So, would anyone be able to point me in the direction of any good simple code templates for calling external programs and redirecting stdin
and stdout
? Thanks.
推荐答案
如果你必须使用处理
,那么像这样的东西应该工作:
If you must use Process
, then something like this should work:
public static void pipeStream(InputStream input, OutputStream output)
throws IOException
{
byte buffer[] = new byte[1024];
int numRead = 0;
do
{
numRead = input.read(buffer);
output.write(buffer, 0, numRead);
} while (input.available() > 0);
output.flush();
}
public static void main(String[] argv)
{
FileInputStream fileIn = null;
FileOutputStream fileOut = null;
OutputStream procIn = null;
InputStream procOut = null;
try
{
fileIn = new FileInputStream("test.txt");
fileOut = new FileOutputStream("testOut.txt");
Process process = Runtime.getRuntime().exec ("/bin/cat");
procIn = process.getOutputStream();
procOut = process.getInputStream();
pipeStream(fileIn, procIn);
pipeStream(procOut, fileOut);
}
catch (IOException ioe)
{
System.out.println(ioe);
}
}
注意:
- 确保
关闭
流 - 将此更改为使用缓冲流,我认为原始的
输入/输出流程
实现可能一次复制一个字节。 - 处理过程可能会改变,具体取决于您的具体流程:
cat
是管道I / O最简单的示例。
- Be sure to
close
the streams - Change this to use buffered streams, I think the raw
Input/OutputStreams
implementation may copy a byte at a time. - The handling of the process will probably change depending on your specific process:
cat
is the simplest example with piped I/O.
这篇关于使用重定向的stdin和stdout从Java运行外部程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!