Java BufferedReader

https://w‮w‬w.theitroad.com

Java BufferedReader is a class that reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. It is a higher-level class that provides more functionality than the lower-level FileReader and InputStreamReader classes.

Here's an example of how to use BufferedReader to read from a file:

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

In this example, we create a new BufferedReader object and pass it a FileReader object that reads from the file "example.txt". We then use a while loop to read each line of the file and print it to the console. Note that we use a try-with-resources statement to automatically close the BufferedReader when we're done with it, and we catch any IOException that might occur during the read operation.

The BufferedReader class provides several methods that can be used to read from the input stream:

  1. read(): This method reads a single character from the input stream and returns it as an integer. If the end of the stream has been reached, it returns -1.

  2. read(char[] cbuf, int off, int len): This method reads up to len characters from the input stream into the cbuf character array, starting at the specified off offset. It returns the number of characters read, or -1 if the end of the stream has been reached.

  3. readLine(): This method reads a line of text from the input stream and returns it as a string. If the end of the stream has been reached, it returns null.

  4. skip(long n): This method skips over and discards up to n characters of data from the input stream.

  5. ready(): This method returns true if the input stream is ready to be read, false otherwise.

  6. close(): This method closes the input stream and releases any system resources associated with it.