stdout java,通过写入stdout并从stdin读取来传递参数,从Java调用exe

But I additionally want to pass parameters to stdin of external process and read from stdout of this process.

How can I do this?

My efforts:

main method:

public class ProcessBuilderTest {

public static void main(String[] args) throws IOException, InterruptedException {

ProcessBuilder pb = new ProcessBuilder("C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java",

"-cp", //class path key

"C:\\Users\\redwhite\\IdeaProjects\\HelloMyWorld\\out\\production\\HelloMyWorld" , // path to class file of ExternalProcess class

"call_external.ExternalProcess"); // fully qualified name

Process process = pb.start();

OutputStream processOutputStream = process.getOutputStream();

IOUtils.write("1" + System.lineSeparator(), processOutputStream);

InputStream processInputStream = process.getInputStream();

System.out.println("--1--");

System.out.println(process.isAlive()); // outputs true

String result = IOUtils.toString(processInputStream, "UTF-8"); //

System.out.println("--2--");

process.waitFor();

System.out.println(result); // expect to see processed[1]

}

}

ExternalProcess await string from stdin and produce another string to stdout:

package call_external;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

/**

* Created by redwhite on 27.03.2017.

*/

public class ExternalProcess {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String input = br.readLine();

System.out.println("processed[" + input + "]");

}

}

This code hangs.I cannot understand why

解决方案

Instead of adding \n in the end of line, stream should be closed

thus after replacing

IOUtils.write("1" + System.lineSeparator(), processOutputStream);

with

IOUtils.write("1", processOutputStream);

processOutputStream.close();

Code became work properly

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值