Reputation: 4273
To generate some uniqueness in file system names of user-provided files, I generate a hash value of some other user-supplied data (in this case the user's IP address and a random integer) and prefix the filename with it. I chose the SHA-1 algorithm to perform this hash. Unfortunately, the String returned from
md = MessageDigest.getInstance("SHA-1");
// Add values to the digest
String ipAddrHash = new String(md.digest());
...of course contains all sorts of weird exotic characters, most of which are not allowed in file names.
So, either:
Upvotes: 0
Views: 2645
Reputation: 716
You can encode returned String with Base32 or Base64 with replacing "/" character with safe one (for example: "_").
Upvotes: 0
Reputation: 121961
If it is only uniqueness use a java.util.UUID
. FWIW, I had a similar requirement and this is what I used to solve it (software operating on both linux and windows). A UUID contains alphanumerics and hyphens only so no issues with incompatible file system characters and guarantees uniqueness.
Upvotes: 1
Reputation: 691625
You could encode the bytes in hexadecimal to get a printable file name. But your algorithm doesn't guarantee uniqueness.
Or you could simply use a UUID, or a sequence number returned from a database sequence.
Upvotes: 3