我试图通过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的参数,被识别为主命令。
尝试用/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();
只需调用您要运行的命令即可。