我尝试从Java运行多个命令shell。我能够做到这一点(并使用PrintWriter在控制台中获取输出)。但是,我希望能够在单独的String中获取每个命令的输出。这可能吗?
以下是代码的一部分:
File wd = new File("/bin");
Process proc = null;
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
out.println("cd ..");
out.println("ls");
System.out.println("moving to /var directory");
out.println("cd /var/");
out.println("ls");
//get output of ls command in string variable
out.println("cd ..");
out.println("cd /etc/");
out.println("ls -a");
out.println("ps");
out.println("exit");
try {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
}
catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:0)
您是否尝试过像
这样的部分StringBuilder builder = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
builder.append(line).append("\n");
}
String commandOutput = builder.toString();
每个命令后?这大致是你想要实现的目标吗?