【问题标题】:android EMFILE (Too many open files)android EMFILE(打开的文件太多)
【发布时间】:2012-08-14 15:58:10
【问题描述】:

我实现了一个文件缓存来为长网格视图加载小图像。滚动一段时间后,我得到了很多libcore.io.ErrnoException: open failed: EMFILE (Too many open files)

如何避免这种情况?这是读取一个位图的代码:

File fullCacheDir = new File(Environment.getExternalStorageDirectory().toString(), cacheDir);
File file = new File(fullCacheDir.toString(), fileName);

if (!file.exists()) {
    return null;
}

Bitmap bm = BitmapFactory.decodeFile(file.toString());

这是保存一个位图:

FileOutputStream outputStream = new FileOutputStream(fileUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();

【问题讨论】:

    标签: android file


    【解决方案1】:

    您的 close() 调用是否有可能由于异常而未到达?我一般是这样编码的:

    try {
      new FileOutputStream(fileUri);
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
      outputStream.flush();
    } finally {
      try {
        outputStream.close();
      } catch (Exception ignored) {
        // ignore exceptions generated by close()
      }
    }
    

    我看不出第一个代码片段有任何明显错误。

    【讨论】:

    • 只是一个更新:Apache Commons 有一个 closeQuietly() 实用程序,它将关闭 Closeable 并吞下异常。我发现这非常有用,即使 Apache Commons 不可用,我 roll my own
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 2019-08-11
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    相关资源
    最近更新 更多