0

Need advise on how to implement pipes in Java. Eg,

echo "test"|wc

I need to show results of the above pipe example.

I have tried this:

public class myRunner {

  private static final String[] cmd = new String[] {"wc"};
  public static void main(String[] args){       
    try {
        ProcessBuilder pb = new ProcessBuilder( cmd );
        pb.redirectErrorStream(true);           
        Process process = pb.start();
        OutputStream os = process.getOutputStream();
        os.write("echo test".getBytes() );
        os.close();
    }catch (IOException e){
        e.printStackTrace();
    }

How can I view the output of wc output?

I believe another one of the library i can use is PipedInputStream/PipedOutputStream. Can anyone show an example on how to use it? Am quite confused. thanks

dorothy
  • 1,213
  • 5
  • 20
  • 35
  • 4
    Can you post what you've tried, what you expect it to do and what it does? – Elliott Frisch Aug 06 '14 at 02:54
  • see http://www.jguru.com/faq/view.jsp?EID=464749 – Leo Aug 06 '14 at 02:58
  • Check this post to get clarity of PipedInputSteam[http://stackoverflow.com/questions/3395714/use-cases-of-pipedinputstream-and-pipedoutputstream?lq=1] – randominstanceOfLivingThing Aug 06 '14 at 03:42
  • `PipedInput/OutputStreams` are irrelevant to this problem. They are for communicating between threads, not between processes, and when between threads you are almost invariably better off using a Queue of some kind, as stated in my answer to @SureshKoya's cited thread. – user207421 Aug 06 '14 at 04:20

2 Answers2

1

How can I view the output of wc output?

By consuming the Process's output, via Process.getInputStream(), and reading from it.

user207421
  • 305,947
  • 44
  • 307
  • 483
0
public ArrayList<String> executorPiped(String[] cmd, String outputOld){
    String s=null;
    ArrayList<String> out=new ArrayList<String>();

    try {
        ProcessBuilder pb = new ProcessBuilder( cmd );
        pb.redirectErrorStream(true);
        Process p = pb.start();
        OutputStream os = p.getOutputStream();
        os.write(outputOld.getBytes());
        os.close();

        BufferedReader stdInput = new BufferedReader(new
                InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
                InputStreamReader(p.getErrorStream()));

        while ((s = stdInput.readLine()) != null) {
            out.add(s);
        }
    }catch (IOException io){

    }
    return out;
}
Abhi
  • 11
  • 2