user142162
user142162

Reputation:

System.console() with file input

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.

Upvotes: 2

Views: 784

Answers (2)

user unknown
user unknown

Reputation: 36229

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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499800

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.

Upvotes: 4

Related Questions