【问题标题】:writeDataToFile(String) may fail to clean up java.io.Writer on checked exception in FindBugswriteDataToFile(String) 在 FindBugs 中检查异常时可能无法清理 java.io.Writer
【发布时间】:2018-12-21 11:08:17
【问题描述】:

我正在使用 FileWrite 类写入文件。它工作正常。但是 FindBugs 在我的代码 sn-p 中指出了一个小问题。

代码 sn-p:

  SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";
        FileWriter writer = null;
        try {
            File root = new File(Environment.getExternalStorageDirectory(), "Test");
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, fileName);

            writer = new FileWriter(gpxfile, true);
            writer.append(text + "\n\n");

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

查找错误报告:

OBL_UNSATISFIED_OBLIGATION:方法可能无法清理流或资源 writeDataToFile(String) 在检查异常时可能无法清理 java.io.Writer

我在哪一行收到此错误?

  writer = new FileWriter(gpxfile, true);

有人可以简要介绍一下这到底是什么吗? 我们该如何解决这个问题?

【问题讨论】:

    标签: android findbugs


    【解决方案1】:

    由于writer.flush();,您收到此错误。这可能会导致 IOException,因为它将任何缓冲输出写入底层流。如果发生异常,writer 将不会被关闭。

    如果强制刷新finally{..},则为每一行使用专用的try{..} catch{..},如下所示:

    finally {
        if (writer != null) {
            try {
                writer.flush();                
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

    • 谢谢你:-),这个问题已经解决了,但是在同一行我又得到了一个 findbugs 警告说“发现依赖默认编码:新的 java.io.FileWriter(File, boolean)”。你能帮我吗?
    • @kavie 你可以看看这个SO
    • 如果我使用 String 我可以使用一些默认编码方法,但是这里我将 File 作为第一个参数传递对吗?
    • @kavie 似乎指向了一个事实,即简单地使用 append 将使用默认编码。有一种方法可以更改编码,如SO 所示。但是,您可能需要做一些额外的工作。如果链接没有帮助,我建议您为其创建新问题。
    猜你喜欢
    • 2014-07-20
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 2014-08-21
    相关资源
    最近更新 更多