Any Java way to generate recognition strings similar to Youtube Video strings?

Each video on YouTube has a unique identification string, such as 1cru2fzulec

Is there any Java method that can generate something close to it? Off I mean that strings are unique, short, and use numbers and letters (case sensitive)

I need to use such a string as YouTube uses: identify records in the back-end system I'm working on a Java Web application I don't want to use it http://example.com?id=123 The method of

I know that the UUID implementation of Java can produce similar results, but it is too long compared with YouTube

thank you!

Edit 1:

Thank you very much for your reply All your input is useful! There seems to be no perfect solution Any perfect (if not UUID) must be generated and checked (to avoid duplication) Am I right?

I'm sure YouTube will face the same problem as Java people when generating its own 12 character video string?

Cheers!

Edit 2:

I want to use a full range of alphanumeric characters, not just hexadecimal numbers I will use Marcus Junius Brutus's solution I think it's intuitive and safe enough In theory, I'll have to check every generated string, but I won't because each check is another database call I will add a unique constraint to the table field for the generated string ID I might fail that unfortunate user the first time I generate a record What he needs to do is go back to the form, fill it in again and save it (I hope it won't fail the second time because of repeated string values) Initially I'll use a 12 - char string, which I can easily increase when I need it

I will use this solution for distributed web applications that communicate with the same back-end database, which means multiple JVMs for the same application

This is my solution and I hope it will work

String sampleAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    Random random = new Random();
    char[] buf = new char[12];
    for (int i = 0 ; i < 12 ; i++)
        buf[i] = sampleAlphabet.charAt(random.nextInt(sampleAlphabet.length()));
    return new String(buf);

Thank you for your reply They are all acceptable solutions I really appreciate it

Best for you!

Solution

Why don't you try this? It meets all your needs

https://github.com/peet/hashids.java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>