5

我想groff在 Java 程序中运行。输入来自一个字符串。在实际命令行中,我们将^D在 Linux/Mac 中终止输入。那么如何在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);

还是有其他想法?

4

2 回答 2

7

^D不是一个字符;这是一个由你的 shell 解释的命令,告诉它关闭进程的流(因此进程收到 EOF on stdin)。

你需要在你的代码中做同样的事情;冲洗并关闭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();
...
于 2013-07-21T14:19:56.080 回答
1

我写了这个实用方法:

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();
}
于 2015-10-07T08:07:52.300 回答