【问题标题】:How to properly close file-to-string input stream? (IOUtils FileUtils)如何正确关闭文件到字符串的输入流? (IOUtils FileUtils)
【发布时间】:2013-07-01 03:51:27
【问题描述】:

我的应用中有两个文件到字符串的进程(一个实际上处理资产文件)。
如果我在同一个文件上多次重复这些过程中的任何一个,我就会得到 OutOfMemoryErrors。
我怀疑这可能是因为我没有正确关闭流,因此可能导致创建多个流,这可能导致我的应用程序内存不足。
下面是两个进程的代码:

我的资产文件到字符串的过程。
如您所见,我有一些东西可以关闭流,但我不知道它的格式是否正确。

try 
{
      myVeryLargeString = IOUtils.toString(getAssets().open(myAssetsFilePath), "UTF-8");
      IOUtils.closeQuietly(getAssets().open(myAssetsFilePath));
} 
catch (IOException e) 
{
      e.printStackTrace();
}
catch(OutOfMemoryError e)
{
      Log.e(TAG, "Ran out of memory 01");
}



我的文件到字符串的过程。
我不知道如何关闭这个流(如果甚至有一个流要关闭的话)。

myFile01 = new File(myFilePath);
try 
{
      myVeryLargeString = FileUtils.readFileToString(myFile01, "UTF-8");
} 
catch (IOException e) 
{
      e.printStackTrace();
}
catch(OutOfMemoryError e)
{
      Log.e(TAG, "Ran out of memory 02");
}

【问题讨论】:

  • IOUtils 和 fileutils 是你的课吗??
  • 我猜你打开流两次然后关闭它getAssets().open(myAssetsFilePath) 看起来很可疑
  • 考虑将close() 调用放在finally 块中。
  • @Ashish Aggarwal:我不确定你在问什么。
  • @BevynQ 虽然这两个进程都导致了 OutOfMemoryErrors;不只是资产之一。另外,如果你认为那段代码是可疑的,你可能知道我应该把它改成什么吗?谢谢。

标签: java android out-of-memory assets fileutils


【解决方案1】:

很难说是什么导致了OOME,但是关闭应该是这样的

InputStream is = getAssets().open(myAssetsFilePath);
try {
    myVeryLargeString = IOUtils.toString(is, "UTF-8");
} finally {
    IOUtils.closeQuietly(is);
}

【讨论】:

  • 感谢您的回答。您是否也有关闭我发布的第二个流程的建议? (FileUtils 进程)是否有需要关闭的流?
  • 不,FileUtils.readFileToString 在内部关闭 InputStream
  • Eclipse 不允许我使用这种格式。它希望 getAssets() 部分位于 try/catch 中。
  • 你可以使用try-catch-finally。或者干脆声明包含代码的方法抛出 IOException
  • 你的意思是我应该在包含 getAssets() 的行周围创建一个额外的 try/catch 吗?如果是这样,两个 try/catch 应该都有 finally + closeQuietly,还是只有第一个 try/catch?
猜你喜欢
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多