唯一地创建子文件

Creating subfiles uniquely

我有问题。

我有一个名为 abc 的文件。在处理这个文件时,我会得到一些其他文件,这些文件会有一些独特的信息,比如标签或一些值。我想将它们命名为 abc#unique_id。它就像一个 perfect/injective 哈希函数。我不能使用普通的散列函数,因为我可能会发生散列冲突。我正在考虑生成一个随机数并检查是否存在这样命名的文件,如果存在则生成另一个数字。但是如果有更多的文件,这可能会降低效率。

考虑将当前 time/date 添加到文件名的末尾。 System.currentTimeMillis(); 将获取当前时间作为 Long,并且您很可能同时获取超过 1 个文件(精确到毫秒)。

更多信息here

你也可以使用计数器。这是一个 class 使用它的简单示例。请注意,getName 是同步的,以便在多线程环境中也为计数器变量授予正确的值。

public class FileHelper {
    private static int counter = 0;

    static {
        init();
    }

    private static init() {
       // load last counter value from database, 
       // scanning files in the directory or saving it to a property file.
    }

    public static synchronized String getName() {
        counter++;
        return "name_" + counter;
    }
}

如果需要存储上次使用的计数器,可以添加一个初始化函数来加载上次使用的计数器,例如从数据库中加载,或者扫描创建文件的目录,或者将其保存到 属性 文件。

您可以使用 File.createTempFile(String prefix, String suffix, File directory)。来自 javadoc:

Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:

  • The file denoted by the returned abstract pathname did not exist before this method was invoked, and

  • Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.

在你的情况下,你想做这样的事情:

File newFile = File.createTempFile("abc#", ".ext", new File("/path/to/your/directory/"));
// use newFile