gpt4 book ai didi

java - 如果出现 FileNotFoundException,是否应该关闭输出流?还有 IOException?

转载 作者:太空狗 更新时间:2023-10-29 13:15:36 25 4
gpt4 key购买 nike

我有这个代码:

   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 block 中关闭 FileOutputStream

如果抛出该异常意味着无法打开文件,所以我认为没有必要。但是,我认为在 IOException catch block 中执行此操作会很好。

如果我不这样做,会不会导致任何内存泄漏错误或类似的错误?

谢谢。

最佳答案

如果您在 Java 7 或更高版本中工作,您应该使用尝试使用资源并让系统决定。

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

关于java - 如果出现 FileNotFoundException,是否应该关闭输出流?还有 IOException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35012570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com