當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。