BufferedWriter关闭抛出异常

时间:2015-06-12 23:15:38

标签: java android exception bufferedwriter

我已经制作了一种在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;
}

是吗?为什么呢?

1 个答案:

答案 0 :(得分:2)

关闭out会导致所有基础流和作者关闭,因此调用:

fw.flush();
fw.close();
调用out.close()

是多余的,因为此时fw已经关闭。

这导致了第二个问题,即fw.flush()已关闭时调用fw ...调用' flush()'在已经关闭的流或作者上通常会导致例外情况,例如您正在看到的异常。

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