java - 从用户那里获取输入

标签 java io

ScannerBufferedReader 获取输入有什么区别?

这是一个 BufferedReader 示例...

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");

// read characters
do {
    c = (char) br.read();
    System.out.println(c);
} while(c != 'q');

这是一个Scanner 示例...

Scanner scan = new Scanner(System.in);
char mrArray = new char[10];
// read characters
for (int i = 0; i < myArray.length; i++) {
    String temp = myScanner.next();
    myArray[i] = temp.charAt(0);
}

这两种情况有什么区别吗?这些类(class)中的任何一个将来可能会发生变化吗?我应该优先使用 BufferedStream 而不是 Scanner 吗?

最佳答案

A BufferedReader is a simple class meant to efficiently read from the underling stream. Generally, each read request made of a Reader like a FileReader causes a corresponding read request to be made to underlying stream. Each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Efficiency is improved appreciably if a Reader is warped in a BufferedReader.
BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads.

A scanner on the other hand has a lot more cheese built into it; it can do all that a BufferedReader can do and at the same level of efficiency as well. However, in addition a Scanner can parse the underlying stream for primitive types and strings using regular expressions. It can also tokenize the underlying stream with the delimiter of your choice. It can also do forward scanning of the underlying stream disregarding the delimiter! A scanner however is not thread safe, it has to be externally synchronized.

来源:Scanner vs buffer reader

关于java - 从用户那里获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10192349/

相关文章:

java - 如何使用jetty-maven-plugin公开静态内容?

java - Apache Tomcat server.xml 组件的启动顺序

java - 带有 git 和 Maven 的 Eclipse 资源文件夹

java - Intellij 资源子文件夹不包含在类路径中

c - C 语言的低级编写

java - 如何将 SoapUI 的功能引入到 Android 项目中

go - scanner.Scan() 在 Linux 但不是 Windows 上阻塞直到退出

c++ - 修改日志类以接受字符串中的变量 - C++

c - C中的read函数只读取3072字节

perl - 为什么Programming Perl中 "7.2.39 IPC::Open2"所示的程序居然结束了?