Try this:
/** Execute a command where each parameter is in the string array. It is better to
* do such a call this way because passing a single string to the java
* Runtime.getRuntime().exec("single long string") method invokes StringTokenizer
* to split the string into an array of strings and it does a poor job at it.
*
* I.e. The string:
* ksh -c "mkdir /tmp/test"
*
* is split thus:
*
* ksh
* -c
* "mkdir
* /tmp/test"
*
* and then the shell interpreter complains about unmatched quotes.
*
* Returns a list which is whatever was put
* on the stdout, followed by what was put on stderr.
* @param exec the execution array, the first entry is the executable to run.
* Don't forget that shell builtin command must be run within a shell.
* @return The output list.
*/
public List executeExactCommand(String exec[])
{
int exitCode = 3; // Assume we failed
List execOutput = new ArrayList();
String execCmd = "";
int i;
for (i = 0; i < exec.length; ++i) {
execCmd += (((i != 0) ? " " : "") + exec[i]);
}
try {
Process p = Runtime.getRuntime().exec(exec);
try {
InputStream is = p.getInputStream();
StringBuffer desc;
int chr = 0;
while (chr >= 0) {
desc = new StringBuffer(5192);
chr = is.read();
for (i = 0; (i < 5192) && (chr >= 0) && (chr != '\n'); chr = is.read()) {
// Because of Bill Gates, everyone in the world has to
// process for a possible, useless, RETURN character.
if (chr != '\r') {
desc.append((char) chr);
++i;
}
}
if ((chr >= 0) || (desc.length() != 0)) {
execOutput.add(desc.toString());
}
}
is = p.getErrorStream();
chr = 0;
while (chr >= 0) {
desc = new StringBuffer(5192);
chr = is.read();
for (i = 0; (i < 5192) && (chr >= 0) && (chr != '\n'); chr = is.read()) {
// Because of Bill Gates, everyone in the world has to
// process for a possible, useless, RETURN character.
if (chr != '\r') {
desc.append((char) chr);
++i;
}
}
if ((chr >= 0) || (desc.length() != 0)) {
execOutput.add(desc.toString());
}
}
exitCode = p.waitFor();
if (withCommandTrace) {
execOutput.add("execCmd = " + execCmd + " (" + exitCode + ")");
}
}
catch (InterruptedException x) {
System.err.println("Error command interupted, cmd='" + execCmd + "'");
System.err.println("Caught: " + x);
execOutput.add("Error command interupted, cmd='" + execCmd + "'");
execOutput.add("" + exitCode);
}
}
catch (IOException x) {
// couldn't exec command
System.err.println("Error executing command, command=" + execCmd);
System.err.println("Caught: " + x);
execOutput.add("Error executing command, cmd='" + execCmd + "'");
execOutput.add("" + exitCode);
}
if (withCommandTrace) {
for (i = 0; (execOutput != null) && (i < execOutput.size()); ++i) {
System.out.println((String) execOutput.get(i));
}
}
return execOutput;
}
You would call it using something like this:
List eachOutputLines = executeExactCommand(["bash", "-c", "ls -la /"]);