ChatGPT解决这个技术问题 Extra ChatGPT

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.

You could start with this thread in stackoverflow, where temp-files are discussed.
This Android Developers Google group discussion might be of interest: groups.google.com/group/android-developers/browse_thread/thread/…

M
Martin Zeitler

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.


That's what I do as well. My assumption is that createTempFile does not create real temporary files unless it uses the cache dir, but this not really documented.
can i assume the file will remain as long as the app is running, even if other apps also run and create their own temporary files ?
Every app uses it's own cache: By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). If you'd like to cache some data, you should use getCacheDir() to open a File where your application should save temporary cache files. When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. Source
Can I use share intent to share this file?
You can call outputFile.deleteOnExit() . In theory, the system will clean it up when your app exits. Standard method in File class.
A
Antonio

Best practices on internal and external temporary files:

Internal Cache

If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files. When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.

External Cache

To open a File that represents the external storage directory where you should save cache files, call getExternalCacheDir(). If the user uninstalls your application, these files will be automatically deleted. Similar to ContextCompat.getExternalFilesDirs(), mentioned above, you can also access a cache directory on a secondary external storage (if available) by calling ContextCompat.getExternalCacheDirs(). Tip: To preserve file space and maintain your app's performance, it's important that you carefully manage your cache files and remove those that aren't needed anymore throughout your app's lifecycle.


This does not adequately answer the question of what to do with large temporary files. What is the best practice here? I suspect there isn't one, other than simply managing a normal file.
r
ra1ned

For temporary internal files their are 2 options

1.

File file; 
file = File.createTempFile(filename, null, this.getCacheDir());

2.

File file
file = new File(this.getCacheDir(), filename);

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 as internal_file and comes out as internal_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 via file.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.


Can I assume that the temporary files will only be deleted when the app's process isn't alive?
@androiddeveloper No.
@GuilhermeBernal How do you know that? Have you seen it getting deleted?
@androiddeveloper Sorry for not giving details earlier. A user can open the app, then go to settings, clear its cache and then go back to the app, all without having it killed. So an app can't assume the cache file won't be deleted and nothing stops android itself doing so without user interaction.
T
TheRealChx101

You can use the cache dir using context.getCacheDir().

File temp=File.createTempFile("prefix","suffix",context.getCacheDir());

File temp=File.createTempFile("prefix","suffix",context.getCacheDir());
Thanks, I did it, but my file size equals 0B, where the problem is, any ideas ?
k
kotucz

You can use the File.deleteOnExit() method

https://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)


It is pretty much useless on Android due to strange flavor of JVM used (It's almost never terminate normally)
As long there are no performance concerns, delete, free or drop data immediatly, when you don't need it anymore.
S
Shivam Dawar

Do it in simple. According to documentation https://developer.android.com/training/data-storage/files

String imageName = "IMG_" + String.valueOf(System.currentTimeMillis()) +".jpg";
        picFile = new File(ProfileActivity.this.getCacheDir(),imageName);

and delete it after usage

picFile.delete()