Java Character Streams: BufferedReader, InputStreamReader and Resource leakage
In the world of programming, many times we need to read the input from an external source, such as a file or keyboard.
BufferedReader reads text from a character-input stream to provide efficient reading of characters, arrays, and lines. BufferedReader is best used with an underlying reader whose read operation in itself is inefficient, but when wrapped around by a BufferedReader, it becomes highly efficient. The underlying stream reader can be any FileReaders or the InputStreamReader.
You can find more information related to it on the official link here.
Reading from byte input streams
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));
The InputStreamReader accepts an object of InputStream in its constructor. This InputStream has the following implementations that can be used as per the use-case:
AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream
Closing the streams
In order to avoid any resource leakages, it is important to close the streams that you have opened in your code.
- If you are using Java 7 or above, the best way to do it is using try-with-resources.
try(BufferedReader br
= new BufferedReader(new InputStreamReader(System.in)))
{
return br.readLine();
}
catch()
{}
In here, the class BufferedReader
, in Java SE 7 and later, implements the interface java.lang.AutoCloseable
. Because the BufferedReader
instance is declared in a try
-with-resource statement, it will be closed regardless of whether the try
statement completes normally or abruptly.
2. If you are using Java 6 or below, you can use finally block to make sure the streams are closed.
static String readFromFile() {try
{
FileReader fileReader = new Filereader(path); InputStreamReader inputSRdr = new InputStreamReader(fileReader); BufferedReader br = new…