我的应用程序中有两个文件到字符串的进程(一个实际上处理 Assets 文件)。
如果我对同一个文件重复这些过程中的任何一个几次,我会得到 OutOfMemoryErrors。
我怀疑这可能是因为我没有正确关闭流,因此可能导致创建多个流,这可能导致我的应用程序内存不足。
下面是两个进程的代码:
我的 Assets 文件到字符串的过程。
如您所见,我已经准备好关闭流,但我不知道它的格式是否正确。
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");
}
最佳答案
很难说什么会导致OOME,但关闭应该是这样的
InputStream is = getAssets().open(myAssetsFilePath);
try {
myVeryLargeString = IOUtils.toString(is, "UTF-8");
} finally {
IOUtils.closeQuietly(is);
}
关于java - 如何正确关闭文件到字符串的输入流? (IOUtils FileUtils),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17397189/