![](/img/trans.png)
[英]Communicate with external C program with Java using stdin and stdout
[英]Running external program with redirected stdin and stdout from Java
我正在尝试从Java程序运行外部程序,我遇到了麻烦。 基本上我想做的就是:
Runtime.getRuntime().exec("./extprogram <fileIn >fileOut");
但是我发现这不起作用--Java表达式需要使用带有输入和输出流的Process
以及其他我没有遇到过的东西。
我已经看过互联网上的一些例子(其中很多来自SO),并且似乎没有一种简单的标准方法可以做到这一点,对于那些不完全了解正在发生的事情的人来说,可能会非常令人沮丧。
我也无法尝试从其他人的代码示例中构建自己的代码,因为通常看起来大多数其他人对重定向stdin
不感兴趣,而且2.不一定将stdout
重定向到文件,但是而不是System.out
。
那么,是否有人能够指出任何好的简单代码模板的方向来调用外部程序并重定向stdin
和stdout
? 谢谢。
你可以尝试这样的事情:
ProcessBuilder pb = new ProcessBuilder();
pb.redirectInput(new FileInputStream(new File(infile));
pb.redirectOutput(new FileOutputStream(new File(outfile));
pb.command(cmd);
pb.start().waitFor();
如果你必须使用Process
,那么这样的东西应该工作:
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);
}
}
注意:
close
溪流 Input/OutputStreams
实现可以一次复制一个字节。 cat
是管道I / O的最简单示例。 你试过System.setIn和System.setOut吗? 自JDK 1.0以来一直存在。
public class MyClass
{
System.setIn( new FileInputStream( "fileIn.txt" ) );
int oneByte = (char) System.in.read();
...
System.setOut( new FileOutputStream( "fileOut.txt" ) );
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.