在java中运行系统命令

时间:2016-10-17 00:01:28

标签: java command-line terminal

我对为什么我无法运行以下命令感到有点困惑ls -l 如果我运行lspwd,则可以正常运行。

我错过了什么吗?

    ProcessBuilder pb = new ProcessBuilder("ls -l");
    pb.redirectErrorStream(true);
    Process process = pb.start();

    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ( (line = br.readLine()) != null) {
        System.out.println(line);
    }
    br.close();

还有一个问题:如何同时运行多个系统命令?使用while循环或for循环将逐个运行命令。有什么建议吗?

提前致谢。

3 个答案:

答案 0 :(得分:1)

变化:

new ProcessBuilder("ls -l");

要:

new ProcessBuilder("ls", "-l");

答案 1 :(得分:0)

    String[] st = {"ls", "bin"};
    ProcessBuilder pb = new ProcessBuilder(st);
    pb.redirectErrorStream(true);
    Process process = pb.start();

    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ( (line = br.readLine()) != null) {
        System.out.println(line);
    }
    br.close();  

答案 2 :(得分:0)

  

使用while循环或for循环将逐个运行命令。

只有当您为每个人做一整个 start-then-read-stdout 业务时,才会逐个进行。这些过程确实是并行运行的,只是阅读部分阻止你同时运行它们。您需要做的就是打破开始并分为两部分:

    Stream.of(Arrays.asList("ls", "-l"),
              Arrays.asList("python", "-h"),
              Arrays.asList("df"))
            .map(cmd->{
                // Create a process for each command, but don't read the output
                try {
                    return new AbstractMap.SimpleImmutableEntry<>(cmd,
                            new ProcessBuilder(cmd)
                                    .redirectErrorStream(true)
                                    .start().getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            })
            .filter(p->p!=null)
            .parallel()
            .forEach(in->{
                // Read and print STDOUT for each process.
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(in.getValue()))){
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.printf("%20s: %s\n", in.getKey(), line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

parallel()调用使输出真的难以阅读,只是为了证明这些进程真正同时运行。