java shell for executing/coordinating processes?

前端 未结 4 467
萌比男神i
萌比男神i 2021-01-14 06:20

I know about using Runtime.exec, you pass it a native program to run + arguments. If it\'s a regular program, you can run it directly. If it\'s a shell script, you have to r

4条回答
  •  暖寄归人
    2021-01-14 06:49

    You've always been able to handle streams with Runtime.exec

    e.g.

    String cmd = "ls -al";
        Runtime run = Runtime.getRuntime();
        Process pr = run.exec(cmd);
        pr.waitFor();
        BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line = "";
        while ((line=buf.readLine())!=null) {
            System.out.println(line);
        }
    

    However, if you want to put shell characters such as pipe and redirect in there you'd have to write your own command line parser which links up the streams. As far as I know there hasn't one been written. That being said, could you just invoke bash from Java with a -c "ls | sort" for example and then read the input. Hmm time to do some testing.

提交回复
热议问题