如果我遇到FileNotFoundException和IOException,是否应该关闭输出流?

3

我有这段代码:

   private void save(Bitmap bitmap) {
        try {
            FileOutputStream fos = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

我需要在FileNotFoundException catch块中关闭FileOutputStream吗?

如果抛出该异常,则意味着文件无法打开,因此我认为不必要。但是,在IOException catch块中这样做会更好。

如果我不这样做,会导致内存泄漏错误或类似问题吗?

谢谢。


1
在这种情况下,fos未被打开,因此fos将为null。因此没有需要关闭的内容。请尝试。 - greenapps
1
@greenapps 不是 null,只是从未被分配,并且在“catch”块中超出了范围。 - user207421
当然,在catch块之外,你应该从FileOutputStream fos = null;开始。 - greenapps
哦哦哦...那是你啊 EJP。今天会是美好的一天。 - greenapps
3个回答

1
如果您正在使用Java 7或更高版本,应该使用“try with resources”,并让系统自行决定。
private void save(Bitmap bitmap) {
    try (FileOutputStream fos = new FileOutputStream(path)) {
        bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

如果不是,那么请确保流不为null,然后在finally中执行。

private void save(Bitmap bitmap) {
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(path);
        bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

1

没有需要关闭的内容。 FileOutputStream 构造函数抛出了一个异常;流从未被构建;fos 变量从未被分配;并且在 catch 块中超出了作用域。


0

在你完成读取或写入后,应该始终关闭文件。否则,你会一直占用资源,可能会引起问题。
如果你按照这种方式修改你的代码,你就不必担心关闭文件,Java 将为你处理。

    private void save(Bitmap bitmap) {
       try(FileOutputStream fos = new FileOutputStream(path)) {
          bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
       } catch (FileNotFoundException e) {
          e.printStackTrace();
       } catch (IOException e) {
          e.printStackTrace();
       }
    }

不回答问题。如果出现“FileNotFoundException”或任何关闭,您将无法进行任何读写操作。 - user207421

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接