Eu utilizo esse método para executar comandos do sistema, e tem funcionado bem para mim. Nao fui eu que fiz a implementação inicial dele, mas fiz uns ajustes para poder utilizá-lo como método.
Ele retorna o string com a saída do comando, essa saída pode ser uma mensagem de erro ou não.
public static String executaStr(String command, int timeout)
{
Process process = null;
try {
System.out.println("Executing external command " + command);
process = Runtime.getRuntime().exec(command);
}
catch (IOException e) {
System.out.println(e.toString());
return "";
}
InputStream inputStream = process.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
InputStream errorStream = process.getErrorStream();
BufferedInputStream bufferedErrorStream = new BufferedInputStream(errorStream);
boolean ok = false;
int exitValue = -999;
String output = "";
while (!ok) {
try {
byte [] bytes = new byte[1000];
int lido = 0;
while ((bufferedInputStream.available() > 0) || (bufferedErrorStream.available() > 0)) {
System.out.println("bufferedInputStream: ");
while (bufferedInputStream.available() > 0) {
//bufferedInputStream.read();
//System.out.print((char)bufferedInputStream.read());
lido = bufferedInputStream.read(bytes);
for (int i=0 ; i< lido ; i++) {
output += String.valueOf((char)bytes[i]);
}
}
System.out.println("bufferedErrorStream: ");
while (bufferedErrorStream.available() > 0) {
//bufferedErrorStream.read();
//System.out.print((char)bufferedErrorStream.read());
lido = bufferedErrorStream.read(bytes);
for (int i=0 ; i< lido ; i++) {
output += String.valueOf((char)bytes[i]);
}
}
}
}
catch (IOException e) {
System.out.println("Couldn't read response");
}
System.out.println("output: " + output);
try {
exitValue = process.exitValue();
ok = true;
}
catch (IllegalThreadStateException e) {
try {
// still running.
Thread.sleep(300);
timeout = timeout - 300;
if (timeout < 0 && timeout >= -300) {
System.out.println("ALERT: Command doesn't terminate:");
System.out.println(command);
System.out.println("Shutting down command...");
process.destroy();
}
else if (timeout <0) {
System.out.println("ALERT: Command STILL doesn't terminate:");
System.out.println(command);
Thread.sleep(1000);
}
} catch (InterruptedException e1) {
// doesn't matter
}
}
}
if (ok) {
// finished running
if (exitValue == 0) {
//System.out.println("Terminated without errors");
}
else {
//System.out.println("Exit code " + exitValue + " while performing command " + command);
}
}
else {
process.destroy();
}
try {
System.out.println("bufferedInputStream2: ");
while (bufferedInputStream.available() > 0) {
System.out.print((char)bufferedInputStream.read());
}
System.out.println("bufferedErrorStream2: ");
while (bufferedErrorStream.available() > 0) {
System.out.print((char)bufferedErrorStream.read());
}
}
catch (IOException e) {
System.out.println("Couldn't read response");
}
return output;
}