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

查看:37
本文介绍了File.createTempFile() VS new 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 new File()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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