当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java BufferedReader和FileReader的区别用法及代码示例


BufferedReader 和 FileReader 这两个类都用于从给定的字符流中读取数据。它们都有一些优点和一些缺点。在本文中,我们将讨论它们之间的差异。虽然最重要的区别在于它们的工作方式,但我们也会讨论其他细节。

什么是缓冲区?

缓冲区是设备内存的一小部分,用于临时存储一定量的数据。通常,缓冲区使用设备的 RAM 来存储临时数据,因此,从缓冲区访问数据比从硬盘访问相同数量的数据要快得多。

BufferedReader 和 FileReader 之间的差异通过考虑的主要参数进行说明和讨论,如下所示:

  1. Usage
  2. Efficiency
  3. Speed
  4. 读行

1. 使用方法

FileReader 用于从磁盘驱动器读取文件,而 BufferedReader 不仅限于读取文件。它可用于从任何字符流中读取数据。 FileReader类提供了两个构造函数:

  • FileReader(文件文件):它采用代表磁盘中文件的 File 对象并创建一个新的 FileReader 实例。
  • FileReader(FileDescriptor fd):创建一个新的 FileReader,指定要读取的FileDescriptor。
  • FileReader(String fileName):以文件名作为唯一参数,并创建一个新的FileReader实例来读取文件。

BufferedReader类提供了两个构造函数:

  • BufferedReader(Reader rd):它使用 Reader 从字符输入流中读取数据并创建默认大小的输入缓冲区。
  • BufferedReader(Reader rd, int size):采用两个参数:
    • 第一个:一个Reader,用于读取输入流数据
    • 第二:输入缓冲区的大小。它使用给定大小的输入缓冲区创建一个新的BufferedReader。

如图所示,BufferedReader 接受任何类型的 Reader(StringReader、FileReader 等),因此能够从任何字符输入流中读取。而 FileReader 只能从文件中读取字符。通常,我们用BufferedReader包FileReader来从文件中读取字符。

2. 效率

BufferedReader在性能方面比FileReader高效得多。 FileReader直接从文件的字符流中读取数据。每次读取一个字符时,它都会直接访问磁盘驱动器,并且每次磁盘驱动器都需要一些时间才能正确定位读取头,这使得效率非常低。

而 BufferedReader 创建一个输入缓冲区,并允许从硬盘驱动器读取大块数据而不是一次读取一个字节的输入,从而显著提高性能。默认缓冲区大小为 8Kb(在大多数情况下足够了),但可以自定义。 BufferedReader 一次读取大量数据并将其存储在创建的缓冲存储器中。当java.io.BufferedReader#read()被调用时,它从内存缓冲区读取数据。当缓冲区中没有数据时,它会向底层字符流发出相应的读取请求,并将大量数据加载到创建的缓冲区中。因此,我们在读取每个字符时不必直接访问硬盘,我们可以从缓冲存储器中读取,速度更快,效率更高。

3. 速度

由于BufferedReader内部使用缓冲区,该类比FileReader快得多。 BufferReader不需要像FileReader那样每次都访问硬盘,因此速度更快。

4. 阅读台词

在大多数情况下,您希望一次读取一行而不是一次读取一个字符,并且只有 BufferedReader 提供一次读取整行的 readLine() 方法。简单地说,给定的 Reader(在本例中为 FileReader)读取字符并将它们存储在缓冲区中。当调用 java.io.BufferedReader#readLine() 方法时,存储在缓冲区中的一行字符将以字符串形式返回。它节省了大量时间,因此比 FileReader#read() 方法更快。需要注意的是,BufferedReader之所以能够一次读取整行,是因为它使用了缓冲存储器,它可以将一行的字符存储在缓冲区中,并直接从缓冲区中一起读取所有字符。

结论:BufferedReader 和 FileReader 之间的差异

基础 缓冲读取器 文件阅读器
Use 它用于从任何类型的字符输入流(字符串、文件,ETC。) 只能用于读取文件
Buffer 在内部使用 Buffer 来读取字符 不使用缓冲区。通过访问硬盘直接读取文件。
Speed Faster Slower
Efficiency 读取文件效率更高 效率较低
阅读台词 BufferedReader 可用于一次读取一个字符以及一次读取一行。 一次只能读取一个字符,不能读取行

执行:

示例 1:使用BufferedReader读取行

Java


// Java Program to differentiate between
// BufferedReader and FileReader in Java
// Reading lines using BufferedReader
// Import necessary classes
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
// Class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        FileReader reader;
        // Try block to check exceptions
        try {
            // A Reader that reads creates an input
            // character stream
            // and reads characters from it
            reader = new FileReader("geeks.txt");
            // Creating a BufferedReader object (instance)
            //  that 16Kb in buffer in the memory
            BufferedReader buffer
                = new BufferedReader(reader, 16384);
            // Custom input
            // A string to store the lines
            String line = "";
            // Maintaining real time count using
            // currentTimeMillis() method to get time taken
            // to read the data
            long initialTime = System.currentTimeMillis();
            while (true) {
                // Try block to check exceptions
                try {
                    // readLine() method of BufferedReader
                    // returns
                    //  a whole line at a time
                    line = buffer.readLine();
                }
                // Catch block to handle exceptions
                catch (IOException e) {
                    // Print the line where exception
                    // occurred
                    e.printStackTrace();
                }
                // When the read head reaches the "End Of
                // File" the readLine method returns null
                if (line == null)
                    break;
                // Prints the line
                System.out.println(line);
            }
            // New line
            System.out.println();
            // Display the time taken to read the data
            System.out.println("Time taken : "
                               + (System.currentTimeMillis()
                                  - initialTime));
            // Try block to check exceptions
            try {
                // Close all the streams
                buffer.close();
                reader.close();
            }
            // Catching only exceptions those occurred
            // only during closing streams
            catch (IOException e) {
                // Prints the line number where exception
                // occurred
                e.printStackTrace();
            }
        }
        // Catch block
        catch (FileNotFoundException e) {
            // print the exception only if
            // the file not found
            e.printStackTrace();
        }
    }
}


输出:来自上述程序中使用的本地目录中的文件“geeks.txt”

Hello geeks!

BufferedReader uses a FileReader to read data from this file.

BufferedReader creates a input buffer with the given size (if no such size given then the default size is 8Kb).

If we use only the FileReader, then it reads one character at a time by directly accessing the disk drive.

Each time it reads the data, it takes some time for the disk drive to position the read head correctly which makes it very inefficient.

Accessing the disk drive every time for reading a single character affects the performance.

Whereas, BufferedReader creates a buffer, and reads large amount of data using the given FileReader and loads it into a input buffer in the memory.

Each time you want to read the file data, you can read it from the buffer( you don’t have to directly access the disk drive every time) and hence is faster than FileReader.  

Time taken : 3

示例 2:仅使用 FileReader 读取行

Java


// Java Program to differentiate between
// BufferedReader and FileReader in Java
// Reading lines using FileReader
// Import necessary classes
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
// Class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        FileReader reader;
        // Try block to check if exception occurred
        try {
            // A FileReader to read data from "geeks.txt"
            // File present in local directory
            reader = new FileReader("geeks.txt");
            char ch;
            // An integer to store the integer
            // returned by FileReader#read() method
            int i = -1;
            // Stores the initial current time
            long initialTime = System.currentTimeMillis();
            while (true) {
                try {
                    // The read() method of FileReader
                    // reads one character at a time
                    // and returns it as an integer
                    i = reader.read();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                // When the "End Of File" is reached
                // the read() method returns -1
                if (i == -1)
                    break;
                ch = (char)i;
                System.out.print(ch);
            }
            // New line
            System.out.println();
            // Display and print the time taken
            System.out.println("Time taken : "
                               + (System.currentTimeMillis()
                                  - initialTime));
            try {
                reader.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

输出:来自上述程序中使用的本地目录中的文件“geeks.txt”

Hello geeks!

BufferedReader uses a FileReader to read data from this file.

BufferedReader creates a input buffer with the given size (if no such size given then the default size is 8Kb).

If we use only the FileReader, then it reads one character at a time by directly accessing the disk drive.

Each time it reads the data, it takes some time for the disk drive to position the read head correctly which makes it very inefficient.

Accessing the disk drive every time for reading a single character affects the performance.

Whereas, BufferedReader creates a buffer, and reads large amount of data using the given FileReader and loads it into a input buffer in the memory.

Each time you want to read the file data, you can read it from the buffer( you don’t have to directly access the disk drive every time) and hence is much more efficient than FileReader.

Time taken : 32

注意:

  1. 读取过程所需的时间可能因系统而异,但事实是 BufferedReader 比 FileReader 运行得更快、更高效。
  2. 如果你想要好的性能,那么你会同时使用它们。 BufferedReader 本身并不从输入流中读取数据,它使用与本机系统 API 交互的 Reader(通常是 FileReader)从给定的输入源(如果是 FileReader 则为文件)读取字符。 BufferedReader类只是向字符流添加一个缓冲区并从缓冲区读取字符,而不是直接从输入源读取字符。因此,您可以仅使用 FileReader 来读取文件,因为它可以访问硬盘驱动器并从中读取数据。但是你不能使用“only BufferedReader”来读取文件,因为它没有访问硬盘的权限,你必须提供一个具有访问权限的阅读器(FileReader)。


相关用法


注:本文由纯净天空筛选整理自samufo大神的英文原创作品 Difference Between BufferedReader and FileReader in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。