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

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

    Problem is synchronization. Separate out regions of conflict.

    Name the file as : (server-name)_(thread/process-name)_(millisecond/timestamp).(extension)
    example : aws1_t1_1447402821007.png

    0 讨论(0)
  • I use the timestamp

    i.e

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

    And have the simpleDateFormat initialized to something like as:

    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

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

    I use current milliseconds with random numbers

    i.e

    Random random=new Random();
    String ext = ".jpeg";
    File dir = new File("/home/pregzt");
    String name = String.format("%s%s",System.currentTimeMillis(),random.nextInt(100000)+ext);
    File file = new File(dir, name);
    
    0 讨论(0)
  • 2020-11-29 21:24

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

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

    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);
    
    0 讨论(0)
  • 2020-11-29 21:24

    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:

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

    Output filenames should look like :

    2OoBwH8OwYGKW2QE_4Sep2013061732GMT_1378275452253.Ext
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题