I have the following class. It allows me to execute commands through java.
public class ExecuteShellCommand {
public String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
When I run commands, the result of the previous command isn't saved. For example:
public static void main(String args[]) {
ExecuteShellCommand com = new ExecuteShellCommand();
System.out.println(com.executeCommand("ls"));
System.out.println(com.executeCommand("cd bin"));
System.out.println(com.executeCommand("ls"));
}
Gives the output:
bin
src
bin
src
Why doesn't the second 'ls' command show the contents of the 'bin' directory?
exec
and use aProcessBuilder
to create the process.