Home > Blockchain >  Passing shell arguments to java
Passing shell arguments to java

Time:11-27

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

CodePudding user response:

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.

CodePudding user response:

If you are expecting this to work like we do cat <file> | cut -d... kind of thing, it will not happen here. When you pipe the output of one command to another, the other command has to read from stdin.

So, your Java program should read from stdin.

Here's one example.

public class myClass{
    public static void main( String[] args ){
        String input = readIn();

        System.out.println( input );
    }

    private static String readIn(){
        try{
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[ 1024 ];

            int bytesRead = -1;
            while( ( bytesRead = System.in.read( buffer ) ) > 0 ){
                baos.write( buffer, 0, bytesRead );
            }

            return baos.toString( StandardCharsets.UTF_8 );
        }
        catch( IOException e ){
            throw new RuntimeException( e );
        }
    }
}

Now, after you compile this, you can call: $ echo "text" | java myClass

  • Related