如何将EOF发送到Java中的进程?

时间:2013-07-21 14:04:21

标签: java eof groff

我想在Java程序中运行groff。输入来自一个字符串。在实际命令行中,我们将在Linux / Mac中通过^D终止输入。那么如何在Java程序中发送这个终结符呢?

String usage +=
    ".Dd \\[year]\n"+
    ".Dt test 1\n"+
    ".Os\n"+
    ".Sh test\n"+
    "^D\n";    // <--- EOF here?
Process groff = Runtime.getRuntime().exec("groff -mandoc -T ascii -");
groff.getOutputStream().write(usage.getBytes());
byte[] buffer = new byte[1024];
groff.getInputStream().read(buffer);
String s = new String(buffer);
System.out.println(s);

还是其他任何想法?

2 个答案:

答案 0 :(得分:4)

^D不是一个角色;它是由shell解释的命令,告诉它关闭进程的流(因此进程在stdin上接收EOF。)

您需要在代码中执行相同的操作;刷新并关闭OutputStream

String usage =
  ".Dd \\[year]\n" +
  ".Dt test 1\n" +
  ".Os\n" +
  ".Sh test\n";
...
OutputStream out = groff.getOutputStream();
out.write(usage.getBytes());
out.close();
...

答案 1 :(得分:0)

我写了这个实用工具方法:

public static String pipe(String str, String command2) throws IOException, InterruptedException {
    Process p2 = Runtime.getRuntime().exec(command2);
    OutputStream out = p2.getOutputStream();
    out.write(str.getBytes());
    out.close();
    p2.waitFor();
    BufferedReader reader
            = new BufferedReader(new InputStreamReader(p2.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    return sb.toString();
}