How is a stdin redirect compatible utility?

Is there a utility class in some Java library that offers amenities like java.io.Console but is compatible with input bash redirection?

The following code:

import java.io.Console;
public class Foo {
  public static void main(String args[]) {
    Console cons = System.console();
    String foo = cons.readLine(); // line-5
  }
}

will cause NPE on line 5 when executed:

echo "test" | java Foo

This is also mentioned in this discussion of SO , offering no alternatives other than using System.in .

+5
source share
1 answer

Try the following:

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

public class Foo {
    public static void main(String args[]) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String foo = in.readLine(); // line-5
        System.out.println(foo);
    }
}

Password related functions must be performed manually.

+3
source

All Articles