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.
Use java.util.UUID.
String uniqueString = UUID.randomUUID().toString();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With