在 Java 中运行 Bash 命令
2022-09-01 09:44:50
我有以下课程。它允许我通过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();
}
}
当我运行命令时,不会保存上一个命令的结果。例如:
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"));
}
给出输出:
bin
src
bin
src
为什么第二个“ls”命令不显示“bin”目录的内容?