现在我必须下载其网址已知的文件。下载操作完成后,我需要将其保存到SD卡。问题是我应该在下载之前知道该文件是否存在。所以我打算使用从url生成的标识文件名保存文件。所以,当我得到网址时,我可以计算出相应的文件名。我应该使用哪种算法?
BTW,JAVA就是我正在使用的。
也许,我没有清楚地告诉我的要求。从URL“www.yahoo.com/abc.png”获取文件名“abc.png”不是我需要的。因为“www.google.com/abc.png”会生成相同的文件名。我需要从url生成一个唯一的文件名。
答案 0 :(得分: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;
}
}