Differences between file reading classes

3

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.

    
asked by Eduardo Farias 18.05.2017 в 07:24
source

2 answers

2
  • FileReader is used to read character files, ie archives of plain text containing characters ASCII


  • BufferedReader Can also be used to read text files,
    but nevertheless it can be used to read another type of content that does not necessarily come from a text file, in addition to BufferedReader supports UTF .


  • BufferedWriter would also have the same characteristics as BufferedReader only used to write content in files or other sides.


  • FileWriter has the same characteristics as FileReader only it is used to write text in files.
answered by 18.05.2017 / 09:23
source
3

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);
        }
    }
    
answered by 18.05.2017 в 16:21