gpt4 book ai didi

java - 从用户那里获取输入

转载 作者:搜寻专家 更新时间:2023-11-01 01:18:05 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com