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

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

    Why not use synchronized to process multi thread. here is my solution,It's can generate a short file name , and it's unique.

    private static synchronized String generateFileName(){
        String name = make(index);
        index ++;
        return name;
    }
    private static String make(int index) {
        if(index == 0) return "";
        return String.valueOf(chars[index % chars.length]) + make(index / chars.length);
    }
    private static int index = 1;
    private static char[] chars = {'a','b','c','d','e','f','g',
            'h','i','j','k','l','m','n',
            'o','p','q','r','s','t',
            'u','v','w','x','y','z'};
    

    blew is main function for test , It's work.

    public static void main(String[] args) {
        List names = new ArrayList<>();
        List threads = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 1000; i++) {
                        String name = generateFileName();
                        names.add(name);
                    }
                }
            });
            thread.run();
            threads.add(thread);
        }
    
        for (int i = 0; i < 10; i++) {
            try {
                threads.get(i).join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        System.out.println(names);
        System.out.println(names.size());
    
    }
    

提交回复
热议问题