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

后端 未结 16 2238
不思量自难忘°
不思量自难忘° 2020-11-29 20:51

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

相关标签:
16条回答
  • 2020-11-29 21:37
        //Generating Unique File Name
        public String getFileName() {
            String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date());
            return "PNG_" + timeStamp + "_.png";
        }
    
    0 讨论(0)
  • 2020-11-29 21:37

    This also works

    String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
    
    logFileName = "loggerFile_" + logFileName;
    
    0 讨论(0)
  • 2020-11-29 21:41

    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.

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

    0 讨论(0)
  • 2020-11-29 21:41

    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.

    0 讨论(0)
提交回复
热议问题