Take the 2-minute tour ×

I'm retrieving posts from Facebook, I want to save data in database, but for images and photos I need to download them but I need to determine the extension of the image but using splitting is not useful all times since the link differs. Is there a way to determine the extension?

My code:

  public static String DownLoadFile(String netUrl, String savePath, String name, String ext) {
        try {
            URL url = new URL(netUrl);
            File file = new File(savePath, name + "." + ext);

   /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();

        InputStream is = ucon.getInputStream();

        BufferedInputStream bis = new BufferedInputStream(is);
        long startTime = System.currentTimeMillis();
        Log.d("DownloadManager", "download begining");
        Log.d("DownloadManager", "downloaded file name:" + name);

        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);

           /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

        return file.getAbsolutePath();

    } catch (Exception exx) {
        if (exx.getMessage() != null) {

            Log.w(Error_Tag, "Err3 = " + exx.getMessage());
        } else {



    return null;
share|improve this question
I see the problem concerning split, but couldnt you just extract like the last 5-10 characters of your link and split them? –  Philipp Jahoda Aug 11 '13 at 9:19
add comment

1 Answer

MimeTypeMap.getFileExtensionFromUrl is what you are looking for.

share|improve this answer
thnx.But if i want to save the image by its id how can i get it from the url. –  jaradat Aug 12 '13 at 12:15
One way is to use the (getPath) method from which you can get the file name. –  Rajesh Aug 12 '13 at 13:09
but when i run the code it gives this error: open failed: ENOENT (No such file or directory).i added write permission on external storage –  jaradat Aug 13 '13 at 10:04
add comment

Your Answer


