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

时间:2017-03-27 16:23:22

标签: java exe stdout stdin processbuilder

我读过这个问题: Java Programming: call an exe from Java and passing parameters

这个答案已经足够了 https://stackoverflow.com/a/5604756/2674303

但我还想将参数传递给外部进程的stdin,并从此进程的stdout读取。

我该怎么做?

我的努力

主要方法:

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"); //<-- hangs here
        System.out.println("--2--");
        process.waitFor();
        System.out.println(result); // expect to see processed[1]
    }
}

ExternalProcess等待来自stdin的字符串并生成另一个字符串 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 + "]");
    }
}

此代码挂起。我无法理解为什么

3 个答案:

答案 0 :(得分:0)

我不知道IOUtils类是什么以及toString()方法正在做什么。但是,从InputStream读取的方法是:

InputStreamReader isr;
BufferedReader br;

String input = "";
String line;

try {

  isr = new InputStreamReader( p.getInputStream );
  br = new BufferedReader( isr );

  while( (line = br.readLine()) != null ) {
    input += line + "\n";
  }

} catch( Exception e ) {
  e.printStackTrace();
}

答案 1 :(得分:0)

如果我很好理解你的问题,那么你正在寻找Java中的popen等效函数。也许这个讨论可以帮助你:)

Java: popen()-like function?

答案 2 :(得分:0)

不应在行尾添加\n,而应关闭流 因此在更换后

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

IOUtils.write("1", processOutputStream);
processOutputStream.close();

代码正常运作