【发布时间】:2014-11-09 16:51:16
【问题描述】:
我有以下课程。它允许我通过 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”目录的内容?
【问题讨论】:
-
另请参阅When Runtime.exec() won't,了解有关正确创建和处理流程的许多好技巧。然后忽略它引用
exec并使用ProcessBuilder创建进程。 -
你好。我尝试使用您的类在我的 Java 应用程序中执行 Bash 命令,但是当我运行命令“cat”时它返回 null...
标签: java bash runtime.exec