在Android中创建临时文件的最佳方法是什么?

可以文件。使用createTempFile ?文档对此非常模糊。

特别是,不清楚何时使用File创建临时文件。createTempFile被删除。


当前回答

你可以使用context.getCacheDir()来使用缓存目录。

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

其他回答

你可以使用context.getCacheDir()来使用缓存目录。

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

这是我通常做的事情:

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

至于是否删除,我也不是很确定。因为我在缓存的实现中使用了这种方法,所以我手动删除最旧的文件,直到缓存目录大小降至我的预设值。

简单地做。根据文档 https://developer.android.com/training/data-storage/files

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

并在使用后删除

picFile.delete()

您可以使用File.deleteOnExit()方法

https://developer.android.com/reference/java/io/File.html deleteOnExit ()

这里引用https://developer.android.com/reference/java/io/File.html#createTempFile(java.lang.String, java.lang。字符串,java.io.File)

内部和外部临时文件的最佳实践:

内部缓存

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.

外部高速缓存

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.