BufferedWriter closed throws exception

2.2k views Asked by At

I have made a method to write a log in an external storage of Android.

    public int writeLog(String clase, String metodo, Object object){
    try{
        File folder = new File(Environment.getExternalStorageDirectory(), Constants.ROUTE_FILES_TEXT);
        if (!folder.exists()) {
            folder.mkdir();
        }

        FileWriter fw = new FileWriter(folder.toString() + "/log.txt", true);

        BufferedWriter out = new BufferedWriter(fw);
        out.write("Hora: " + TimeService.getCurrentTimeStamp(Constants.TIMESTAMP_PATTERN) + "\n");
        out.write("Clase: " + clase + "\n");
        out.write("Método: " + metodo + "\n");
        out.write("Mensaje: " + object + "\n\n\n");
        out.flush();
        out.close();
        fw.flush();
        fw.close();
    }catch (Exception ex){
        Log.d(TAG, ex.toString());
        return 3;
    }
    return 0;
}

Everything works fine, but the method throws an exception always. The exception is:

06-13 01:00:02.043: D/FileService(14439): java.io.IOException: OutputStreamWriter is closed

But, If I comment the close of the BufferedWriter then the method works fine and I haven't got any exception in my code.

    public int writeLog(String clase, String metodo, Object object){
    try{
        File folder = new File(Environment.getExternalStorageDirectory(), Constants.ROUTE_FILES_TEXT);
        if (!folder.exists()) {
            folder.mkdir();
        }

        FileWriter fw = new FileWriter(folder.toString() + "/log.txt", true);

        BufferedWriter out = new BufferedWriter(fw);
        out.write("Hora: " + TimeService.getCurrentTimeStamp(Constants.TIMESTAMP_PATTERN) + "\n");
        out.write("Clase: " + clase + "\n");
        out.write("Método: " + metodo + "\n");
        out.write("Mensaje: " + object + "\n\n\n");
        out.flush();
        //out.close();
        fw.flush();
        fw.close();
    }catch (Exception ex){
        Log.d(TAG, ex.toString());
        return 3;
    }
    return 0;
}

Is that right? Why?

1

There are 1 answers

1
Mike Laren On BEST ANSWER

Closing out causes all underlying streams and writers to be closed as well, so the calls to:

fw.flush();
fw.close();

are redundant after out.close() has been called because at that point fw is already closed.

This leads to the second problem, which is calling fw.flush() when fw is already closed... calling 'flush()' on a stream or writer that has already been closed usually causes an exception like the one you're seeing.

I suggest that you don't close fw manually and instead use out.close() to close the whole output chain.