Android: Create unique string for file name

Use java.util.UUID. Look at randomUUID that generates a so-called Universally unique identifier.

I don't really understand how you intend to generate a “unique” value with String.hashCode. On what string do you call hashCode? hashCode's purpose is not to generate unique IDs... It's meant to generate a hash code for a string, so if the strings themselves are not unique, the hash codes won't be either.


ChrisJ suggestion to use UUID.randomUUID() is a good alternative; but i'd prefer to have the cache backed up by a database table:

ID (PK) | original filename | original URL

and then using the primary key as filename in cache dir.

If you plan to have lots of files, having a directory tree structure like:

0 
+--- 0
     +---- 01.jpg
     +---- 02.jpg
     +---- ...
     +---- 0f.jpg
+--- 1
     +---- 10.jpg
     +---- ...
     +---- cc.jpg

after converting the primary key to hex could also be a cleaner solution, but you will have to decide a left padding for the filenames, which will be a function of the directory tree depth and the number of files per leaf directory.


Use java.util.UUID.

  String uniqueString = UUID.randomUUID().toString();

Tags:

Random

Android