![](/img/trans.png)
[英]java waiting for output command to finish in ProcessBuilder(“sh”)
[英]Waiting output for forever when running commands with ProcessBuilder on Ubuntu
我正在嘗試使用ProcessBuilder在Ubuntu上獲取命令的執行結果。我試圖從以下技術中獲取輸出結果。 但是沒有顯示結果,程序等待輸出。
執行命令:
String[] args = new String[]{"/bin/bash", "-c", "pandoc -f html - t asciidoc input.html"};
Process process = new ProcessBuilder(args).start();
獲得輸出技術1:
InputStream inputStream = process.getInputStream();
StringWriter stringWriter = new StringWriter();
IOUtils.copy(inputStream, stringWriter, "UTF-8");
// Waiting
String asciidocoutput = writer.toString();
獲得輸出技術2:
BufferedReader reader= new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Waiting
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
ProcessBuilder
的構造函數接受命令,每個后續String均被視為第一個String的參數,該字符串被識別為主要命令。
嘗試用pandoc
替換/bin/bash
,看看是否pandoc
。
在我這邊,我可以在不使用ProcessBuilder的情況下運行任意命令,而是使用Runtime.getRuntime().exec(...)
,如下所示:
public static void main(String[] args) throws Exception {
Process proc = Runtime.getRuntime().exec("cmd /c ipconfig");
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while((line = reader.readLine()) != null){
System.out.println(line);
}
}
獲得預期的輸出:
Configurazione IP di Windows
Scheda Ethernet Ethernet:
Suffisso DNS specifico per connessione:
Indirizzo IPv6 locale rispetto al collegamento . : fe80::fcba:735a:5941:5cdc%11
Indirizzo IPv4. . . . . . . . . . . . : 192.168.0.116
Subnet mask . . . . . . . . . . . . . : 255.255.255.0
Gateway predefinito . . . . . . . . . : 192.168.0.1
Process finished with exit code 0
如果您確實需要使用ProcessBuilder
,則可以通過以下方式定義Process
來實現相同的行為:
Process proc = new ProcessBuilder("ipconfig").start();
只需調用要運行的命令即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.