简体   繁体   中英

How to properly close file-to-string input stream? (IOUtils FileUtils)

I have two file-to-string processes in my app (one actually deals with an asset file).
If I repeat either of these processes a few times on the same file, I get OutOfMemoryErrors.
I suspect it might be because I'm not closing the streams properly and therefore maybe causing multiple streams to be created, and this is perhaps causing my app to run out of memory.
Here is the code of the two processes:

My asset-file-to-string process.
As you can see, I have have something in place to close the stream but I don't know if it's formatted properly.

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



My file-to-string process.
I have no idea how to close this stream (if there is even a stream to close at all).

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

It's difficult to say what may cause OOME but closing should be like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM