在 Java 中生成唯一且简短的文件名的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/825678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:55:48  来源:igfitidea点击:

What is the best way to generate a unique and short file name in Java

javafile

提问by Jeff Bloom

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

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

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.

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

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

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

采纳答案by Pesto

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 prefix, plus 5 or more characters generated by the function).

好吧,您可以使用 3-argument 版本:File.createTempFile(String prefix, String suffix, File directory)它可以让您将它放在您想要的位置。除非你告诉它,Java 不会将它与任何其他文件区别对待。唯一的缺点是文件名保证至少有 8 个字符长(前缀最少 3 个字符,加上函数生成的 5 个或更多字符)。

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.

如果这对你来说太长了,我想你总是可以从文件名“a”开始,然后循环“b”、“c”等,直到找到一个不存在的文件。

回答by Galwegian

Why not just use something based on a timestamp..?

为什么不使用基于时间戳的东西..?

回答by OscarRyz

I use the timestamp

我使用时间戳

i.e

IE

new File( simpleDateFormat.format( new Date() ) );

And have the simpleDateFormat initialized to something like as:

并将 simpleDateFormat 初始化为如下所示:

new SimpleDateFormat("File-ddMMyy-hhmmss.SSS.txt");

EDIT

编辑

What about

关于什么

new File(String.format("%s.%s", sdf.format( new Date() ),
                                random.nextInt(9)));

Unless the number of files created in the same second is too high.

除非同一秒内创建的文件数量太多。

If that's the case and the name doesn't matters

如果是这种情况并且名称不重要

 new File( "file."+count++ );

:P

:P

回答by pgras

Look at the File javadoc, the method createNewFile will create the file only if it doesn't exist, and will return a boolean to say if the file was created.

查看文件 javadoc,方法 createNewFile 只会在文件不存在时创建文件,并返回一个布尔值来说明文件是否已创建。

You may also use the exists() method:

你也可以使用 exists() 方法:

int i = 0;
String filename = Integer.toString(i);
File f = new File(filename);
while (f.exists()) {
    i++;
    filename = Integer.toString(i);
    f = new File(filename);
}
f.createNewFile();
System.out.println("File in use: " + f);

回答by justinhj

How about generate based on time stamp rounded to the nearest millisecond, or whatever accuracy you need... then use a lock to synchronize access to the function.

如何根据四舍五入到最接近毫秒的时间戳或您需要的任何精度生成...然后使用锁来同步对函数的访问。

If you store the last generated file name, you can append sequential letters or further digits to it as needed to make it unique.

如果您存储最后生成的文件名,您可以根据需要在其中附加连续的字母或更多数字以使其唯一。

Or if you'd rather do it without locks, use a time step plus a thread ID, and make sure that the function takes longer than a millisecond, or waits so that it does.

或者,如果您更愿意在没有锁的情况下执行此操作,请使用时间步长加上线程 ID,并确保该函数花费的时间超过一毫秒,或者等待以使其执行。

回答by Lawrence Dol

Combining other answers, why not use the ms timestamp with a random value appended; repeat until no conflict, which in practice will be almost never.

结合其他答案,为什么不使用附加随机值的 ms 时间戳;重复直到没有冲突,这在实践中几乎永远不会发生。

For example: File-ccyymmdd-hhmmss-mmm-rrrrrr.txt

例如:文件-ccyymmdd-hhmmss-mmm-rrrrrr.txt

回答by Tomasz B?achowicz

I'd use Apache Commons Lang library (http://commons.apache.org/lang).

我会使用 Apache Commons Lang 库(http://commons.apache.org/lang)。

There is a class org.apache.commons.lang.RandomStringUtilsthat can be used to generate random strings of given length. Very handy not only for filename generation!

有一个类org.apache.commons.lang.RandomStringUtils可用于生成给定长度的随机字符串。不仅对于文件名生成非常方便!

Here is the example:

这是示例:

String ext = "dat";
File dir = new File("/home/pregzt");
String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext);
File file = new File(dir, name);

回答by Shane

If you have access to a database, you can create and use a sequence in the file name.

如果您有权访问数据库,则可以在文件名中创建和使用序列。

select mySequence.nextval from dual;

It will be guaranteed to be unique and shouldn't get too large (unless you are pumping out a ton of files).

它将保证是唯一的并且不应变得太大(除非您要输出大量文件)。

回答by Peter Anthony

It looks like you've got a handful of solutions for creating a unique filename, so I'll leave that alone. I would test the filename this way:

看起来您有一些用于创建唯一文件名的解决方案,所以我将不理会它。我会这样测试文件名:

    String filePath;
    boolean fileNotFound = true;
    while (fileNotFound) {
        String testPath = generateFilename();

        try {
            RandomAccessFile f = new RandomAccessFile(
                new File(testPath), "r");
        } catch (Exception e) {
            // exception thrown by RandomAccessFile if 
            // testPath doesn't exist (ie: it can't be read)

            filePath = testPath;
            fileNotFound = false;
        }
    }
    //now create your file with filePath

回答by MD. Mohiuddin Ahmed

This works for me:

这对我有用:

String generateUniqueFileName() {
    String filename = "";
    long millis = System.currentTimeMillis();
    String datetime = new Date().toGMTString();
    datetime = datetime.replace(" ", "");
    datetime = datetime.replace(":", "");
    String rndchars = RandomStringUtils.randomAlphanumeric(16);
    filename = rndchars + "_" + datetime + "_" + millis;
    return filename;
}

// USE:

// USE:

String newFile;
do{
newFile=generateUniqueFileName() + "." + FileExt;
}
while(new File(basePath+newFile).exists());

Output filenames should look like :

输出文件名应如下所示:

2OoBwH8OwYGKW2QE_4Sep2013061732GMT_1378275452253.Ext