在Java中生成唯一且简短的文件名的最佳方式是什么? [英] What is the best way to generate a unique and short file name in Java

查看:126
本文介绍了在Java中生成唯一且简短的文件名的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不一定要使用UUID,因为它们相当长。



文件只需在其目录中是唯一的。

$ b一个想法是想使用 File.createTempFile(String prefix,String suffix),但这似乎是错误的,因为该文件是不是暂时的。



需要处理在同一毫秒内创建的两个文件的情况。

解决方案

嗯,你可以使用3参数版本: File.createTempFile(String prefix,String suffix,File directory) code> ,这将让你把它放在你想要的地方。除非你告诉它,否则Java不会对待任何其他文件。唯一的缺点是文件名保证至少为8个字符(后缀最少为3个字符,加上该功能生成的5个或更多字符)。



如果这太长了,我想你总是可以从文件名a开始,循环通过b,c等,直到找到不存在的那个。


I don't necessarily want to use UUIDs since they are fairly long.

The file just needs to be unique within its directory.

One thought which comes to mind is to use File.createTempFile(String prefix, String suffix), but that seems wrong because the file is not temporary.

The case of two files created in the same millisecond needs to be handled.

解决方案

Well, you could use the 3-argument version: File.createTempFile(String prefix, String suffix, File directory) which will let you put it where you'd like. Unless you tell it to, Java won't treat it differently than any other file. The only drawback is that the filename is guaranteed to be at least 8 characters long (minimum of 3 characters for the suffix, plus 5 or more characters generated by the function).

If that's too long for you, I suppose you could always just start with the filename "a", and loop through "b", "c", etc until you find one that doesn't already exist.

这篇关于在Java中生成唯一且简短的文件名的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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