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.
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.
You can use the cache dir using context.getCacheDir().
Best practices on internal and external temporary files:
Internal Cache
External Cache
You can use the
File.deleteOnExit()
methodhttps://developer.android.com/reference/java/io/File.html#deleteOnExit()
It is referenced here https://developer.android.com/reference/java/io/File.html#createTempFile(java.lang.String, java.lang.String, java.io.File)
This is what I typically do:
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.
For temporary internal files their are 2 options
1.
2.
Both options adds files in the applications cache directory and thus can be cleared to make space as required but option 1 will add a random number on the end of the filename to keep files unique. It will also add a file extension which is
.tmp
by default, but it can be set to anything via the use of the 2nd parameter. The use of the random number means despite specifying a filename it doesn't stay the same as the number is added along with the suffix/file extension (.tmp
by default) e.g you specify your filename asinternal_file
and comes out asinternal_file1456345.tmp
. Whereas you can specify the extension you can't specify the number that is added. You can however find the filename it generates viafile.getName();
, but you would need to store it somewhere so you can use it whenever you wanted for example to delete or read the file. Therefore for this reason I prefer the 2nd option as the filename you specify is the filename that is created.