Alex Rivera | Logout

Simple way to convert a URL into a filename

Asked 2012-01-29T17:42:22.293
10

I'm writing an asynchronous image downloader for Android and was just wondering, given an arbitary URL such as:

http://www.android.com/images/brand/droid.gif

What would be the best way to convert the unique url to a filename. I thought about simply splitting the url and grabbing the last section, but I want the filename to be representative of the whole URL. The other alternatives I thought were replacing all the forward slashes with underscores or simply hashing the whole URL and storing this.

If anyone has any ideas I'd love to hear them!

Thanks

Edit
Report

1 Answer

3

This method will be fulfill your requirements. It will generate a name which will represent original URL. You can call generateNameFromUrl(String url) method like this.

    String url = "http://www.android.com/images/brand/droid.gif";
    String uniqueName = generateNameFromUrl(url));

Method is given below:

public static String generateNameFromUrl(String url){

    // Replace useless chareacters with UNDERSCORE
    String uniqueName = url.replace("://", "_").replace(".", "_").replace("/", "_");
    // Replace last UNDERSCORE with a DOT
    uniqueName = uniqueName.substring(0,uniqueName.lastIndexOf('_'))
            +"."+uniqueName.substring(uniqueName.lastIndexOf('_')+1,uniqueName.length());
    return uniqueName;
}

Input: "http://www.android.com/images/brand/droid.gif"
Output: "http_www_android_com_images_brand_droid.gif"

answered 2012-01-29T18:48:30.057

Your Answer