0

我试图从 Java 运行多个命令 shell。我能够做到这一点(并使用 PrintWriter 在控制台中获取输出)。但是,我希望能够在单独的字符串中获取每个命令的输出。那可能吗?

这是代码的一部分:

 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();
    }
4

1 回答 1

0

你试过放一个像

StringBuilder builder = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
    builder.append(line).append("\n");
}
String commandOutput = builder.toString();

在每个命令之后?这大致是您想要实现的目标吗?

于 2012-07-14T18:35:53.640 回答