I have some doubts about the FileReader / bufferedReader and FileWritter / BufferedWritter classes, since I do not have very clear in which moment it is better to use one or the other.
I have some doubts about the FileReader / bufferedReader and FileWritter / BufferedWritter classes, since I do not have very clear in which moment it is better to use one or the other.
To complement FrEqDe's answer , the main difference is how these classes work internally.
FileReader
and FileWriter
serve to read / write plain text files . The functionalities offered are to read the contents of the files and store them in char[]
(character array) or in CharBuffer
(a character buffer that uses an array of characters internally). That is, working with these classes only requires a lower level since they do not interact with String
. BufferedReader
/ BufferedWriter
serve as wrappers (known in the world of design patterns as decorator of other Reader
/ Writer
of text and allow you to read / write a whole group of content for you. For example, BufferedReader
will read in advance contents of the Reader
that it wraps and will store it in a buffer (usually a char[]
) so that it facilitates and improves the performance of the reading of the content of Reader
to future.
Beware that BufferedReader
/ BufferedWriter
are not limited to working only with FileReader
/ FileWriter
respectively, they can also be combined with other implementations such as InputStreamReader
/ OutputStreamWriter
to wrap any type of data stream, which allows reading / writing about network frames ( DataInputStream
/ DataOutputStream
) or when reading the response from a service consumed by HTTP pe when using the Apache HttpComponent library and connect to an url:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://www.google.com");
try (CloseableHttpResponse response = httpclient.execute(httpGet);
BufferedReader br = new BufferedReader(new InputStreamReader( response.getEntity().getContent()))) {
//leer la respuesta del servicio
String linea = "";
while ( (linea = br.readLine()) != null) {
System.out.println(linea);
}
}