27

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?

0

3 Answers 3

24

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for answer it. Actually, what i did is to store the online image to the local. Because each image has unique url, I use url.hashcode to generate the file name. I just wonder if there will be a performance issue to use hashcode to do it. So I want to know the common way how you save the cache file, and make them unique.
That is the whole purpose, to be able to get a unique and specific ID for a specific url. If you create random UUID then you will have to maintain a map of urls and IDs. But hashcode will always return the same id for a particular id.
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
23

Use java.util.UUID.

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

Comments

3

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.

1 Comment

It's implementable. But I already has caching them in different way. And I only cache the file after it was stored in local completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.