如何在Java中向进程发送EOF?

如何在Java中向进程发送EOF?,java,eof,groff,Java,Eof,Groff,我想在Java程序中运行groff。输入来自一个字符串。在real命令行中,我们将在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("

我想在Java程序中运行
groff
。输入来自一个字符串。在real命令行中,我们将在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);
字符串用法+=
“.Dd\\[年]\n”+
“.Dt测试1\n”+
“.Os\n”+
“.Sh测试\n”+

“^D\n”//
^D
不是字符;它是shell解释的命令,告诉它关闭流程的流(因此流程在
stdin
上接收EOF)

您需要在代码中执行同样的操作;刷新并关闭
输出流

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

我写了这个实用方法:

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