如何让我的程序运行并与shell程序交互?

时间:2016-04-14 15:23:19

标签: java ubuntu io terminal processbuilder

我在Ubuntu终端中运行了一个名为ProgramABC的程序,该程序在用户按下CTRL + D之前读取查询,然后将一些数据写入标准输出。它完美地运作:

/path/ProgramABC >> file.txt [enter]
<here I write my query> [enter]
<and I press CTRL+D>
<data is written to file.txt and ProgramABC closes automatically>

我想从Java运行它。我的代码不起作用 - 它创建了file.txt,但是它是空的,所以我想将查询传递给进程并因此传递给ProgramABC是错误的。我做错了什么?这是我的代码的一部分:

    ProcessBuilder builder = new ProcessBuilder("bash","-c","/path/program ABC >> file.txt");
    builder.directory(new File("/another/path/"));
    Process process = builder.start();


    OutputStream stdin = process.getOutputStream();
    InputStream stdout = process.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));

    writer.write("<my query here>");
    writer.write((char)4); //it's CTRL+D, right?
    writer.flush();
    writer.close();

0 个答案:

没有答案