0

I have two simple Java programs and I want to pipe the result of the "Test" to the "Test2".

public class Test{
    public static void main(String args[]){
        System.out.println("Hello from Test");
    }
}

and

public class Test2{
    public static void main(String args[]){
        System.out.printf("Program Test piped me \"%s\"",args[0]);
    }
}

After I compiled both of .java files I tried to run the pipe command from terminal

java Test | java Test2, but I get an ArrayIndexOutOfBoundsException which means that the args array is not initialized?

How can the Test2 application take the outputstream value that Test.main() produced through piping?

1
  • Using > perhaps? Commented Nov 3, 2016 at 14:41

2 Answers 2

4

Pipes connect one program’s standard output to another program’s standard input, not to the other program’s command-line arguments.

The second class will not get the piped output as arguments to its main method; it will get the piped output as its standard input. So you want to read the information from System.in:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Test2 {
    public static void main(String args[])
    throws IOException {
        BufferedReader stdin =
            new BufferedReader(new InputStreamReader(System.in));
        stdin.lines().forEachOrdered(
            line -> String.format("Program Test piped me \"%s\"", line));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

One way is to use xargs:

java Test| xargs -I ARGS java Test2 ARGS

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.