File.createTempFile()VS新File() [英] File.createTempFile() VS new File()

查看:290
本文介绍了File.createTempFile()VS新File()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我添加了以Fragment表示的每天添加和保存图片的可能性.

In my app I added the possibility to add and save pictures for everyday day, represented by a Fragment.

为了将图片保存在SD卡上,我目前使用功能File.createTempFile:

In order to save the picture on the SD card, I currently use the function File.createTempFile:

File imageFile = File.createTempFile(imageFileName, MyApplication.JPEG_FILE_SUFFIX, MyApplication.getAlbumDir());

我实际上也尝试了标准方式:

I actually also tried with the standard way:

File imageFile = new File(MyApplication.getAlbumDir(), imageFileName + MyApplication.JPEG_FILE_SUFFIX);

两者都能正常工作,但就我而言,第一个要好于第二个,因为函数createTempFile在文件名的末尾添加了一个长随机数,使其具有唯一性.

Both are working, but in my case the first one is better than the second one because the function createTempFile adds a long random number at the end of the file name making it unique.

举一个例子,这是我使用这两种方法的结果:

To give you an example, here is what I get with both methods:

使用 createTempFile :IMG_2013-06-18_-1961144729.jpg

使用新文件:IMG_2013-06-18_.jpg

最后我的问题是,继续使用createTempFile保存图片是否安全?还是必须使用标准方法并添加一些代码来生成唯一文件名?应该只用于临时文件吗?

Finally my question is, is it safe to keep using createTempFile to save my pictures or do I have to use the standard way and add some code to generate a unique file name? Should it only be used for temporary files?

我查看了有关该功能的文档,但没有发现有关使用它代替new File的可能后果的任何信息.

I reviewed the documentation about the function but I did not find anything about the possible consequences of using it instead of new File.

谢谢

推荐答案

听起来像您的应用程序正在创建文件,所以您需要保证唯一的文件名.您可以在应用程序中保留某种计数器(保存到首选项或数据库)并使用它.然后,您可以创建更短/更受控制的名称,并自己控制唯一性.或者,您可以使用createTempFile(),这将确保您获得唯一的文件名(但仅获得文件名的部分控制权).听起来好像您更喜欢createTempFile(),所以如果您对它生成的文件名感到满意,则没有理由不继续使用它.除了无法完全控制文件名格式之外,没有其他缺点.

Sounds like your app is creating files, so you need to guarantee unique filenames. You could keep some kind of counter within your app (saved to preferences or DB) and use that. Then you could create shorter/more controlled names, and control uniqueness yourself. Or you can use createTempFile(), which will guarantee you get a unique filename (but you only get partial control of the filename). Sounds like you prefer createTempFile(), so there's no reason not to continue using it if you are happy with the filenames it generates. There's no down side other than not having full control over the filename format.

这篇关于File.createTempFile()VS新File()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆