Android: Create unique string for file name

2020-07-01 11:14发布

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?

3条回答
虎瘦雄心在
2楼-- · 2020-07-01 11:39

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.

查看更多
萌系小妹纸
3楼-- · 2020-07-01 11:46

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.

查看更多
萌系小妹纸
4楼-- · 2020-07-01 11:51

Use java.util.UUID.

  String uniqueString = UUID.randomUUID().toString();
查看更多
登录 后发表回答