2

I would like to make use of java.io.Console. I am trying to do so by invoking System.console(). This works..some of the time.

This is fine when I run my program like so:

java classn

However, I would like to read standard input from a file named input.in. When I try to do so via:

java classn < input.in

I receive a null pointer exception:

Exception in thread "main" java.lang.NullPointerException
        at classn.main(classn.java:9)

Is there a fix so I can use Console along with input from a fix? I realise why it's returning null, I would just like to know if there's a way to hook the Console into what's being passed in via a file.

1
  • Can you post the source of classn so we can help diagnose the problem a little further? Commented Mar 8, 2011 at 13:22

2 Answers 2

4

Well, you'd have to test whether System.console() returned null. If it did, you'd have to work without an interactive console - there's no getting around that. You can use System.in to get the information from the redirected file.

An alternative is to have a command-line option to read appropriate data from the given filename, but then interact with the console for the rest.

Sign up to request clarification or add additional context in comments.

3 Comments

But is there a good reason why System.console() would be null and System.in not be? Why was it designed like that? I believe it would be because it uses platform independent ways to suppress input (ex: readPassword()), but can you confirm this?
@Tim: System.console is designed to return an interactive console, with both read and write capabilities. If you're redirecting input, you don't get that.
in theory (at least on UNIX), System.console could open "/dev/tty".
2

Often, the easyest way is to use the Scanner class, bounded to System. in:

 Scanner sc = new Scanner (System.in);

Call your program

 cat foo | java Sample 

on linux/unix/bsd, or

 type foo | java Sample 

on Windows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.