java.io.Console broken in Eclipse

Today I discovered that java.io.Console doesn't work when running application inside Eclipse. I was writing a trivial application that accepts some configuration from console. On trying to run this in Eclipse I was getting NullPointerException.as the Console object was null. I used Eclipse Indigo(3.6) version. On Googling found that there is an open bug and is not fixed. Looks like nobody ever planned to fix it.See bug 122429 for detail.

User XIMES commented a workaround solution in the bug. It is to use BufferedReader by passing System.in as the input stream. Also to write one can use PrintWriter by passing System.out as the output stream.

Downside to this workaround is that it cannot mast passwords which can be done by java.io.Console. Alternatively one can also look at using java.util.Scanner. One issue I found with Scanner is that pressing enter key is not considered as input and had to enter some value other than carriage return key.

Sample usage

public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(new PrintWriter(System.out),true);
      
        writer.printf("Enter name : ");
        String name = reader.readLine();
        System.out.println("You typed : " + name);

}




Comments

Popular posts from this blog

java.util.logging - Bad level value for property: org.openqa.level

Solaris : Send mail with attachment

Suppressing JExcel warnings