Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Create unique string for file name

Tags:

android

random

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?

like image 798
James Avatar asked Feb 26 '11 11:02

James


3 Answers

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.

like image 78
ChrisJ Avatar answered Nov 20 '22 07:11

ChrisJ


Use java.util.UUID.

  String uniqueString = UUID.randomUUID().toString();
like image 21
Yuliia Ashomok Avatar answered Nov 20 '22 07:11

Yuliia Ashomok


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.

like image 3
guido Avatar answered Nov 20 '22 08:11

guido