I am trying to get execution results of command on Ubuntu with ProcessBuilder.I have tried to get the output result from the following techniques. But there is no result displayed, program waiting without output.
Executing Command:
String[] args = new String[]{"/bin/bash", "-c", "pandoc -f html - t asciidoc input.html"};
Process process = new ProcessBuilder(args).start();
Getting Output Technique 1:
InputStream inputStream = process.getInputStream();
StringWriter stringWriter = new StringWriter();
IOUtils.copy(inputStream, stringWriter, "UTF-8");
// Waiting
String asciidocoutput = writer.toString();
Getting Output Technique 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
's constructor takes in a command and each subsequent String is treated as argument for the first String, recognized as the main command.
Try replacing /bin/bash
with pandoc
, and see if it works.
On my side, I was able to run an arbitrary command without the help of ProcessBuilder, using Runtime.getRuntime().exec(...)
instead, like this:
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);
}
}
Obtaining the expected output:
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
If you really need to use ProcessBuilder
, the same behaviour can be achieved by defining your Process
this way:
Process proc = new ProcessBuilder("ipconfig").start();
simply calling the command you want to run.