有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何正确关闭filetostring输入流?(IOUtils文件utils)

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

我的资产文件转换为字符串的过程
正如您所看到的,我已经准备好关闭流,但我不知道它的格式是否正确

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

共 (1) 个答案

  1. # 1 楼答案

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

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