BufferedReader
and FileReader
are classes that extend from the class Reader
and serve to implement the design pattern decorator . This pattern is characterized by adding functionality dynamically at runtime. What you have with the class java.io.Reader
is a contract that establishes how to read characters from a stream of data (stream). The class FileReader
will read characters from a file (whatever its format). The class BufferedReader
decorates a java.io.Reader
to make it easier to read the characters that exist in that reader when pre-consuming its contents and storing it in a buffer, so as to speed up the reading of the characters in the data flow.
To read the characters of a file, simply do this:
FileReader reader = new FileReader("/ruta/del/archivo.ext");
But the FileReader
does not have any additional method to those of Reader
, so the direct reading of this class would be character by character or a set of characters stored in an array (denoted by the method FileReader#read(char[], int, int)
.
To speed up the performance of the application in these cases, what is usually done is to decorate the instance of FileReader
with an instance of BufferedReader
, like this:
BufferedReader reader = new BufferedReader(new FileReader("/ruta/del/archivo.ext"));
Now, whenever you work with a physical file, a connection to that file is opened and the application is said to be using the file. By not closing this connection via Closeable#close
the operating system will mark that the application continues to use the file, thus generating a problem. Resources must always be closed.
As mentioned by @juliansalas, from Java 7 you can save yourself the call to the close
method when using try-with-resources
. Here is an example:
try (BufferedReader reader = new BufferedReader(new FileReader("/ruta/del/archivo.ext"))) {
//consume los datos del reader
//...
} catch (IOException e) {
//maneja tus excepciones, SIEMPRE
} /*
no es necesario agregar un bloque finally para cerrar los recursos
puesto que esta forma de utilizar try ya cerrará los recursos
por ti y manejará el caso en que la variable 'reader' no haya
sido inicializada
*/