Java Scanner和BufferedReader类的区别
在Java中,Scanner和BufferedReader类是作为读取输入的方式的来源。Scanner类是一个简单的文本扫描器,可以解析原始类型和字符串。它在内部使用正则表达式来读取不同的类型,而另一方面,BufferedReader类从字符输入流中读取文本,对字符进行缓冲,以提供对字符序列的有效读取。
偏心的区别在于通过next()方法读取不同的输入方式,在下面的程序中对类似的输入集进行了论证。
例1 :
// Java Program to Illustrate Scanner Class
// Importing Scanner class from
// java.util package
import java.util.Scanner;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating object of Scanner class to
// read input from keyboard
Scanner scn = new Scanner(System.in);
System.out.println("Enter an integer & a String");
// Using nextInt() to parse integer values
int a = scn.nextInt();
// Using nextLine() to parse string values
String b = scn.nextLine();
// Display name and age entered above
System.out.printf("You have entered:- " + a + " "
+ "and name as " + b);
}
}
输出
Enter an integer & a String
10 John
You have entered:- 10 and name as John
让我们用Buffer类尝试一下,下面是相同的输入,如下所示。
例2 :
// Java Program to Illustrate BufferedReader Class
// Importing required class
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
throws IOException
{
// Creating object of class inside main() method
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter an integer");
// Taking integer input
int a = Integer.parseInt(br.readLine());
System.out.println("Enter a String");
String b = br.readLine();
// Printing input entities above
System.out.printf("You have entered:- " + a
+ " and name as " + b);
}
}
输出
输出解释: 在扫描器类中,如果我们在七个 nextXXX()方法 中的任何一个之后调用n extLine()方法 ,那么nextLine()就不会从控制台读取数值,光标也不会进入控制台,它将跳过这一步。nextXXX()方法是 nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong()和 next()。
在BufferReader类中,没有这样的问题。这个问题只发生在扫描器类中,因为nextXXX()方法忽略了换行符,nextLine()只读到第一个换行符。如果我们在nextXXX()和nextLine()之间再调用一次nextLine()方法,那么这个问题就不会发生,因为nextLine()会消耗换行字符。
提示: 请看这个更正后的程序。这个问题与C/C++中scanf()后面的gets()相同。这个问题也可以通过使用 next() 而不是 nextLine() 来解决,如图所示。
以下是Java中Scanner和BufferedReader类的主要区别
- BufferedReader是同步的,而Scanner则不是。如果我们在工作中使用多线程,就应该使用BufferedReader。
- BufferedReader的缓冲区内存明显比Scanner大。
- 相对于BufferedReader(8KB的字节缓冲区),Scanner的缓冲区很小(1KB的char缓冲区),但这已经足够了。
- 与Scanner相比,BufferedReader的速度更快一些,因为Scanner对输入数据进行解析,而BufferedReader只是读取一串字符。