BufferedWriter 关闭抛出异常

BufferedWriter closed throws exception

我已经制作了一个方法可以在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;
}

一切正常,但方法总是抛出异常。例外情况是:

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

但是,如果我注释 BufferedWriter 的关闭,那么该方法工作正常,我的代码中没有任何异常。

    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;
}

是吗?为什么?

关闭 out 会导致所有底层流和编写器也被关闭,因此调用:

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

在调用 out.close() 之后是多余的,因为此时 fw 已经关闭。

这导致了第二个问题,即在 fw 已经关闭时调用 fw.flush()...在已经关闭的流或编写器上调用 'flush()' 通常会导致一个像你看到的那样的例外。

我建议您不要手动关闭 fw 而是使用 out.close() 关闭整个输出链。