2013-07-21 34 views
4

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

^D不是一个字符;这是一个由shell解释的命令,告诉它关闭进程的流(因此进程接收到EOF 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(); 
... 
+0

你能用http://stackoverflow.com/q/43051640/2674303帮助吗? – gstackoverflow

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