Java BufferedReader
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:
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.read(char[] cbuf, int off, int len)
: This method reads up tolen
characters from the input stream into thecbuf
character array, starting at the specifiedoff
offset. It returns the number of characters read, or -1 if the end of the stream has been reached.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 returnsnull
.skip(long n)
: This method skips over and discards up ton
characters of data from the input stream.ready()
: This method returnstrue
if the input stream is ready to be read,false
otherwise.close()
: This method closes the input stream and releases any system resources associated with it.