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

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

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


当前回答

您可以使用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)

其他回答

您可以使用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)

你可以使用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);

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

对于临时内部文件,有两个选项

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.

简单地做。根据文档 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()