Using Java ProcessBuilder to Execute a Piped Command

后端 未结 2 628
悲&欢浪女
悲&欢浪女 2020-11-29 05:17

I\'m trying to use Java\'s ProcessBuilder class to execute a command that has a pipe in it. For example:

ls -l | grep foo

How

相关标签:
2条回答
  • 2020-11-29 05:44

    This should work:

    ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", "ls -l| grep foo");
    

    To execute a pipeline, you have to invoke a shell, and then run your commands inside that shell.

    0 讨论(0)
  • 2020-11-29 05:54

    The simplest way is to invoke the shell with the command line as the parameter. After all, it's the shell which is interpreting "|" to mean "pipe the data between two processes".

    Alternatively, you could launch each process separately, and read from the standard output of "ls -l", writing the data to the standard input of "grep" in your example.

    0 讨论(0)
提交回复
热议问题