gpt4 book ai didi

java - StrictMode 提示 InputStream 没有被关闭

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:04:16 29 4
gpt4 key购买 nike

我收到了 StrictMode 报告的以下违规行为在 Android 中。

02-05 04:07:41.190: ERROR/StrictMode(15093): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks. 02-05 04:07:41.190: ERROR/StrictMode(15093): java.lang.Throwable: Explicit termination method 'close' not called

关于没有正确关闭流的问题很糟糕。但是,关闭 in 不应该关闭底层流吗?标记错误的原因可能是什么?

    private ArrayList<Uri> loadPath() {
ArrayList<Uri> uris = new ArrayList<Uri>();
if (mFile.exists()) {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new BufferedInputStream(
new FileInputStream(mFile), STREAM_BUFFER_SIZE));
ArrayList<String> strings = new ArrayList<String>();
strings.addAll((ArrayList<String>) in.readObject());
for (String string : strings) {
uris.add(Uri.parse(string));
}
} catch (Exception e) {
mFile.delete();
} finally {
IOUtils.closeQuietly(in);
}
}
return uris;
}

public static void closeQuietly(InputStream input) {
try {
if (input != null) {
input.close();
}
} catch (IOException ioe) {
// ignore
}
}

最佳答案

查看源代码,ObjectInputStream 的构造函数和 BufferedInputStream可以抛出异常,导致在下一行分配 FileInputStream 对象,但 in 变量仍为空:

            in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(mFile),
STREAM_BUFFER_SIZE)
);

因为当我们到达 finally block 时 in 为 null,打开的 FileInputStream 对象将不会被您的 closeQuietly 关闭() 方法,导致 StrictMode 最终报错 :)

我建议的最简单的修复方法是将该分配分成 3 个变量并在每个变量上调用 closeQuietly(),可能是这样的:

private ArrayList<Uri> loadPath() {
final ArrayList<Uri> uris = new ArrayList<Uri>();
if (mFile.exists()) {
ObjectInputStream ois = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(mFile);
bis = new BufferedInputStream(fis, STREAM_BUFFER_SIZE);
ois = new ObjectInputStream(bis);
final ArrayList<String> strings = new ArrayList<String>();
strings.addAll((ArrayList<String>) ois.readObject());
for (final String string : strings) {
uris.add(Uri.parse(string));
}
} catch (final Exception e) {
mFile.delete();
} finally {
closeQuietly(fis);
closeQuietly(bis);
closeQuietly(ois);
}
}
return uris;
}

关于java - StrictMode 提示 InputStream 没有被关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9515465/

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