2013-07-21 21 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(); 
} 
相關問題