通过写入stdout并从stdin读取来传递参数,从Java调用exe [英] Call an exe from Java with passing parameters with writing to stdout and reading from stdin

查看:488
本文介绍了通过写入stdout并从stdin读取来传递参数,从Java调用exe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读此问题:
Java编程:从Java调用exe并传递参数

这个答案足够好
https://stackoverflow.com / a / 5604756/2674303

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

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

我该怎么做?

我的努力

主要方法:

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

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

推荐答案

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

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

代码工作正常

这篇关于通过写入stdout并从stdin读取来传递参数,从Java调用exe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆