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

后端 未结 16 2348
不思量自难忘°
不思量自难忘° 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:24

    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
    

提交回复
热议问题