📜  bufferedreader java (1)

📅  最后修改于: 2023-12-03 14:59:35.140000             🧑  作者: Mango

BufferedReader in Java

BufferedReader is a Java class that allows you to read text from a character stream with efficiency and ease. The BufferedReader class reads text from an input stream or a file and buffers the text to reduce the number of reads and writes to the underlying resources.

Initializing a BufferedReader object

To initialize a BufferedReader object, you will need to pass in a Reader object. Here's an example of how to initialize a BufferedReader object to read from a FileReader:

try {
    BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
} catch (IOException e) {
    e.printStackTrace();
}
Reading text using BufferedReader

Once you have created a BufferedReader object, you can use it to read text from an input stream or a file. The most commonly used method for reading text with BufferedReader is the readLine() method. This method reads the next line of text from the input stream and returns it as a String.

Here's an example of how to use the readLine() method to read text from a file:

try {
    BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
    String line = reader.readLine();
    while(line != null) {
        System.out.println(line);
        line = reader.readLine();
    }
} catch (IOException e) {
    e.printStackTrace();
}

This code reads each line of text from the file "file.txt" and prints it to the console.

Closing a BufferedReader object

Once you have finished reading from a BufferedReader, you should close the object to release the resources that it is holding. Here's an example of how to close a BufferedReader object:

try {
    BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
    // do something with the BufferedReader
    reader.close();
} catch (IOException e) {
    e.printStackTrace();
}
Conclusion

BufferedReader is a powerful Java class that makes it easy to read text from an input stream or a file. Its efficient buffering capabilities make it an excellent choice for reading large amounts of text with minimal resource usage.