0

现在我必须下载一个 url 已知的文件。下载操作完成后,我需要将其保存到 SD 卡中。问题是我应该在下载之前知道文件是否存在。因此,我计划使用从 url 生成的已识别文件名保存文件。所以当我得到网址时,我可以计算出他对应的文件名。我应该使用哪种算法?

顺便说一句,我正在使用 JAVA。

也许,我没有把我的要求说清楚。从网址“www.yahoo.com/abc.png”获取文件名“abc.png”不是我需要的。因为“www.google.com/abc.png”会产生相同的文件名。我需要从 url 生成一个唯一的文件名。

4

1 回答 1

0

完整的示例工作...几天前我尝试过自己..我相信它会有所帮助..

package com.imagedownloader;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class ImageDownloaderActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Bitmap bitmap=DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
        ImageView img =(ImageView)findViewById(R.id.imageView1);
        img.setImageBitmap(bitmap);

    }


    private Bitmap DownloadImage(String URL) {
        // TODO Auto-generated method stub
        Bitmap bitmap=null;
        InputStream in=null;
        try {

        in=OpenHttpConnection(URL);
        bitmap=BitmapFactory.decodeStream(in);

            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return bitmap;
    }

    private InputStream OpenHttpConnection(String stingurl) throws IOException {
        // TODO Auto-generated method stub
        InputStream in=null;
        int response=-1;

            URL url = new URL(stingurl);
            URLConnection conn=url.openConnection();



            if(!(conn instanceof HttpURLConnection))
                    throw new IOException("not and http exception");

            try{

                HttpURLConnection httpconn=(HttpURLConnection)conn;
                httpconn.setAllowUserInteraction(false);
                httpconn.setInstanceFollowRedirects(true);
                httpconn.setRequestMethod("GET");
                httpconn.connect();

                response=httpconn.getResponseCode();
                if(response==HttpURLConnection.HTTP_OK)
                {
                    in=httpconn.getInputStream();

                }

            }
            catch(Exception ex)
            {throw new IOException("Error connecting");   }
        return in;
    }
}
于 2012-05-15T11:20:33.997 回答