Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.Console - like utility that's compatible with stdin redirection?

Tags:

java

Is there a utility class in some Java library offering amenities like those of java.io.Console but compatible with Bash pipe redirection of input?

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 throw a NPE on line-5 when doing a:

echo "test" | java Foo

This is also mentioned in this SO discussion without offering any alternatives save the use of System.in.

like image 921
Marcus Junius Brutus Avatar asked Oct 21 '22 18:10

Marcus Junius Brutus


1 Answers

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);
    }
}

The password related features should be done manually.

like image 184
Haim Sulam Avatar answered Nov 02 '22 06:11

Haim Sulam