Skip to content
Advertisement

Passing shell arguments to java

I want to pass input to java in a Bash shell:

$: echo "text" | java myClass

This is my Java code:

public class myClass {

    public static void main(String[] args) {
        if (args.length > 0) {
            System.out.println("argument: " + args[0]);
        }
        else {
            System.out.println("[Error] No argument given");
            System.exit(1);
        }
        System.exit(0);
    }
}

The result is:

$: echo "text" | java myClass
[Error] No argument given

Advertisement

Answer

This is more of a shell programming problem.

You need to write:

$: java myClass $(echo "text")

This will convert the output of echo to parameters. This will work as along as the output of your program is simple (e.g., a short list of words).

If you are expecting to read lines of text you will have to use your original command and read the input from stdin.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement