Java Scanner 与 BufferedReader

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2231369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:00:59  来源:igfitidea点击:

Scanner vs. BufferedReader

javafile-iojava.util.scannerbufferedreader

提问by Mads Mob?k

As far I know, the two most common methods of reading character-based data from a file in Java is using Scanneror BufferedReader. I also know that the BufferedReaderread files efficiently by using a buffer to avoid physical disk operations. My questions are:

据我所知,在 Java 中从文件中读取基于字符的数据的两种最常用方法是使用ScannerBufferedReader。我也知道BufferedReader通过使用缓冲区来有效地读取文件以避免物理磁盘操作。我的问题是:

  • Does Scannerperforms as well as BufferedReader?
  • Why would you choose Scannerover BufferedReaderor vice versa?
  • 是否Scanner执行以及BufferedReader
  • 你为什么要选择ScannerBufferedReader反之亦然?

采纳答案by Chandra Sekar

Scanneris used for parsing tokens from the contents of the stream while BufferedReaderjust reads the stream and does not do any special parsing.

Scanner用于从流的内容中解析令牌,而BufferedReader只是读取流而不做任何特殊的解析。

In fact you can pass a BufferedReaderto a scanneras the source of characters to parse.

实际上,您可以将 a 传递BufferedReader给 ascanner作为要解析的字符源。

回答by BalusC

In currently latest JDK6 release/build (b27), the Scannerhas a smaller buffer (1024 chars) as opposed to the BufferedReader(8192 chars), but it's more than sufficient.

在当前最新的 JDK6 版本/构建 (b27) 中,与(8192 个字符)相比,Scanner缓冲区更小(1024 个字符),但已经绰绰有余。BufferedReader

As to the choice, use the Scannerif you want to parsethe file, use the BufferedReaderif you want to readthe file line by line. Also see the introductory text of their aforelinked API documentations.

至于选择,Scanner如果你想解析文件,使用BufferedReader如果你想逐行读取文件。另请参阅其上述 API 文档的介绍性文本。

  • Parsing= interpreting the given input as tokens (parts). It's able to give back you specific parts directly as int, string, decimal, etc. See also all those nextXxx()methods in Scannerclass.
  • Reading= dumb streaming. It keeps giving back you all characters, which you in turn have to manually inspect if you'd like to match or compose something useful. But if you don't need to do that anyway, then reading is sufficient.
  • 解析= 将给定的输入解释为标记(部分)。它能够直接将特定部分作为 int、string、decimal 等返回给您。另请参阅类中的所有这些nextXxx()方法Scanner
  • 阅读= 愚蠢的流媒体。它不断向您返回所有字符,如果您想匹配或编写一些有用的东西,您又必须手动检查这些字符。但是,如果您无论如何都不需要这样做,那么阅读就足够了。

回答by Roman

  1. BufferedReader will probably give you better performance (because Scanner is based on InputStreamReader, look sources).ups, for reading from files it uses nio. When I tested nio performance against BufferedReader performance for big files nio shows a bit better performance.
  2. For reading from file try Apache Commons IO.
  1. BufferedReader 可能会为您提供更好的性能(因为 Scanner 基于 InputStreamReader,请查看源代码)。ups,从文件中读取它使用 nio。当我针对大文件的 BufferedReader 性能测试 nio 性能时,nio 显示出更好的性能。
  2. 要从文件中读取,请尝试使用 Apache Commons IO。

回答by Evgeniy

I suggest to use BufferedReaderfor reading text. Scannerhides IOExceptionwhile BufferedReaderthrows it immediately.

我建议BufferedReader用于阅读文本。ScannerIOExceptionBufferedReader立即把它扔了。

回答by Jomoos

See this link, following is quoted from there:

请参阅此链接,从那里引用以下内容:

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.

The choice of using a BufferedReader or a Scanner depends on the code you are writing, if you are writing a simple log reader Buffered reader is adequate. However if you are writing an XML parser Scanner is the more natural choice.

Even while reading the input, if want to accept user input line by line and say just add it to a file, a BufferedReader is good enough. On the other hand if you want to accept user input as a command with multiple options, and then intend to perform different operations based on the command and options specified, a Scanner will suit better.

BufferedReader 是一个简单的类,旨在有效地从底层流中读取。通常,像 FileReader 这样的 Reader 发出的每个读取请求都会导致对底层流发出相应的读取请求。每次调用 read() 或 readLine() 都可能导致从文件中读取字节,转换为字符,然后返回,这可能非常低效。如果 Reader 在 BufferedReader 中变形,则效率会显着提高。

BufferedReader 是同步的,因此可以从多个线程安全地完成对 BufferedReader 的读取操作。

另一方面,扫描仪内置了更多的奶酪;它可以完成 BufferedReader 可以做的所有事情,并且效率也相同。但是,此外,扫描器可以使用正则表达式解析基本类型和字符串的底层流。它还可以使用您选择的分隔符标记底层流。它还可以不考虑分隔符对底层流进行前向扫描!

然而,扫描器不是线程安全的,它必须是外部同步的。

选择使用 BufferedReader 还是 Scanner 取决于您正在编写的代码,如果您正在编写一个简单的日志阅读器 Buffered reader 就足够了。但是,如果您正在编写 XML 解析器,则 Scanner 是更自然的选择。

即使在读取输入时,如果想逐行接受用户输入并说只是将其添加到文件中,BufferedReader 就足够了。另一方面,如果您想接受用户输入作为具有多个选项的命令,然后打算根据指定的命令和选项执行不同的操作,则 Scanner 将更适合。

回答by Sujith PS

  1. BufferedReaderhas significantly larger buffer memory than Scanner. Use BufferedReaderif you want to get long strings from a stream, and use Scannerif you want to parse specific type of token from a stream.

  2. Scannercan use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReadercan only read and store String.

  3. BufferedReaderis synchronous while Scanneris not. Use BufferedReaderif you're working with multiple threads.

  4. Scannerhides IOException while BufferedReaderthrows it immediately.

  1. BufferedReader具有比 Scanner 大得多的缓冲内存。使用BufferedReader,如果你想从一个流长字符串,使用Scanner,如果你想从流分析特定类型的标记。

  2. Scanner可以使用自定义分隔符进行标记化并将流解析为原始类型的数据,而BufferedReader只能读取和存储字符串。

  3. BufferedReader是同步的,而Scanner不是。使用BufferedReader,如果你正在使用多线程工作。

  4. Scanner隐藏 IOException 并BufferedReader立即抛出它。

回答by KNU

The answer below is taken from Reading from Console: JAVA Scanner vs BufferedReader

下面的答案来自从控制台读取:JAVA Scanner vs BufferedReader

When read an input from console, there are two options exists to achieve that. First using Scanner, another using BufferedReader. Both of them have different characteristics. It means differences how to use it.

从控制台读取输入时,有两个选项可以实现。先用Scanner,再用BufferedReader。两者都有不同的特点。这意味着如何使用它的差异。

Scanner treated given input as token. BufferedReader just read line by line given input as string. Scanner it self provide parsing capabilities just like nextInt(), nextFloat().

扫描器将给定的输入视为令牌。BufferedReader 只是将输入作为字符串逐行读取。Scanner 它自己提供解析功能,就像 nextInt()、nextFloat() 一样。

But, what is others differences between?

但是,其他之间的区别是什么?

  • Scanner treated given input as token. BufferedReader as stream line/String
  • Scanner tokenized given input using regex. Using BufferedReader must write extra code
  • BufferedReader faster than Scanner *point no. 2
  • Scanner isn't synchronized, BufferedReader synchronized
  • 扫描器将给定的输入视为令牌。BufferedReader 作为流线/字符串
  • 扫描仪使用正则表达式标记给定的输入。使用 BufferedReader 必须写额外的代码
  • BufferedReader 比 Scanner 快 *point no。2
  • 扫描仪不同步,BufferedReader 同步

Scanner come with since JDK version 1.5 higher.

扫描仪随 JDK 1.5 版更高。

When should use Scanner, or Buffered Reader?

什么时候应该使用 Scanner 或 Buffered Reader?

Look at the main differences between both of them, one using tokenized, others using stream line. When you need parsing capabilities, use Scanner instead. But, i am more comfortable with BufferedReader. When you need to read from a File, use BufferedReader, because it's use buffer when read a file. Or you can use BufferedReader as input to Scanner.

看看它们之间的主要区别,一个使用标记化,其他使用流线。当您需要解析功能时,请改用 Scanner。但是,我更喜欢使用 BufferedReader。当您需要从文件中读取时,请使用 BufferedReader,因为它在读取文件时使用缓冲区。或者您可以使用 BufferedReader 作为 Scanner 的输入。

回答by manisha mulchandani

There are different ways of taking input in java like:

在java中有不同的输入方式,例如:

1) BufferedReader 2) Scanner 3) Command Line Arguments

1) BufferedReader 2) 扫描器 3) 命令行参数

BufferedReader Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

BufferedReader 从字符输入流中读取文本,缓冲字符以便有效读取字符、数组和行。

Where Scanner is a simple text scanner which can parse primitive types and strings using regular expressions.

其中 Scanner 是一个简单的文本扫描器,它可以使用正则表达式解析原始类型和字符串。

if you are writing a simple log reader Buffered reader is adequate. if you are writing an XML parser Scanner is the more natural choice.

如果您正在编写一个简单的日志阅读器,缓冲阅读器就足够了。如果您正在编写 XML 解析器 Scanner 是更自然的选择。

For more information please refer:

更多信息请参考:

http://java.meritcampus.com/t/240/Bufferedreader?tc=mm69

http://java.meritcampus.com/t/240/Bufferedreader?tc=mm69

回答by thisismydesign

I prefer Scannerbecause it doesn't throw checked exceptions and therefore it's usage results in a more streamlined code.

我更喜欢Scanner它,因为它不会抛出已检查的异常,因此它的使用会产生更精简的代码。

回答by Shiva

The Main Differences:

主要区别:

  1. Scanner
  1. 扫描器


  • A simple text scanner which can parse primitive types and strings using regular expressions.
  • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
  • 一个简单的文本扫描器,可以使用正则表达式解析原始类型和字符串。
  • Scanner 使用分隔符模式将其输入分解为标记,默认情况下与空格匹配。然后可以使用各种 next 方法将结果令牌转换为不同类型的值。

Example

例子

 String input = "1 fish 2 fish red fish blue fish";
 Scanner s = new Scanner(input).useDelimiter("\s*fish\s*");
 System.out.println(s.nextInt());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.next());
 s.close(); 

prints the following output:

打印以下输出:

 1
 2
 red
 blue 

The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:

使用此代码可以生成相同的输出,它使用正则表达式一次解析所有四个标记:

 String input = "1 fish 2 fish red fish blue fish";

 Scanner s = new Scanner(input);
 s.findInLine("(\d+) fish (\d+) fish (\w+) fish (\w+)");
 MatchResult result = s.match();
 for (int i=1; i<=result.groupCount(); i++)
     System.out.println(result.group(i));
 s.close(); `




  1. BufferedReader:

    • Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

    • The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

  1. 缓冲阅读器:

    • 从字符输入流中读取文本,缓冲字符以便有效读取字符、数组和行。

    • 可以指定缓冲区大小,也可以使用默认大小。对于大多数用途,默认值足够大。

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

通常,Reader 发出的每个读取请求都会导致对底层字符或字节流发出相应的读取请求。因此,建议将 BufferedReader 包装在任何 read() 操作可能代价高昂的 Reader 周围,例如 FileReaders 和 InputStreamReaders。例如,

BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));

will buffer the input from the specified file. Without buffering, 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. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

将缓冲来自指定文件的输入。如果没有缓冲,每次调用 read() 或 readLine() 都可能导致从文件中读取字节,转换为字符,然后返回,这可能非常低效。使用 DataInputStreams 进行文本输入的程序可以通过用适当的 BufferedReader 替换每个 DataInputStream 来本地化。

Source:Link

来源:链接