java stdin 和stdout,使用重定向的stdin和stdout从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 fileOut");

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.

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.

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.

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);

}

}

Note:

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值