开发者

System.console() with file input

开发者 https://www.devze.com 2023-02-15 17:49 出处:网络
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.

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.开发者_如何学Pythonin

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消