InputStreamReader or Console for Java I/O

喜你入骨 提交于 2019-12-11 06:37:43

问题


To get user input in Java which is the better method?

reader = new BufferedReader(new InputStreamReader(System.in));

or by use of Console--> Console c = System.console();

what is the difference between the two and which one is to be used. Or is there any other better method other than these two?


回答1:


Console was introduced recently to Java (Java 6) to make reading and writing to the command line easier. Therefore, I would use Console.




回答2:


I suggest you Scanner class to get user input from console

Scanner in = new Scanner(System.in);

in.next();
int i = in.nextInt();
float f = in.nextFloat();
double d = in.nextDouble();    
String s = in.nextLine();

and other beautiful methods

but between these two I recommend you Console




回答3:


they are pretty much the same, however, the Console has additional methods for securely reading information from the user (eg. password) and returns a more intuitive result for whether the underlying platform actually does support console operations or is launched in a non-interactive environment




回答4:


IMHO they are total diferent. As the doc says:

Methods to access the character-based console device, if any, associated with the current Java virtual machine.

So the implementation is OS specific and not platform independent (there could be or not).

With Consol even you can not read from stdin:

echo 123 | java Test

If Test is using Console it won't work. So the user MUST give input from the console.



来源:https://stackoverflow.com/questions/4602436/inputstreamreader-or-console-for-java-i-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!