I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over 500K+ generation (my needs don't really require anything much more sophisticated). Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like "AEYGF7K0DM1X"
.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can use the UUID class with its getLeastSignificantBits() message to get 64bit of Random data, then convert it to a radix 36 number (i.e. a string consisting of 0-9,A-Z):
This yields a String up to 13 characters long. We use Math.abs() to make sure there isn't a minus sign sneaking in.
Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out. Just use
uuid.replace("-", "")
Output:
You mention "simple", but just in case anyone else is looking for something that meets more stringent security requirements, you might want to take a look at jpwgen. jpwgen is modeled after pwgen in Unix, and is very configurable.
You can use Apache library for this: RandomStringUtils