I'm doing an android application for image viewer. This app will download the image, and store them in a cache folder.
So, in the cache folder, the image file name must be unique. Currently, I use String.hashCode() to generate the file name.
Are there any other better ways to get unique string?
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:
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:
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.