androidfile-iotemporary-files

Creating temporary files in Android


What's the best way to create a temporary file in Android?

Can File.createTempFile be used? The documentation is very vague about it.

In particular, it's not clear when temporary files created with File.createTempFile are deleted, if ever.


Solution

  • This is what I typically do:

    File outputDir = context.getCacheDir(); // context being the Activity pointer
    File outputFile = File.createTempFile("prefix", ".extension", outputDir);
    

    As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.