根据前文的方法自己写了一个函数,下载的图片有username和id,遂希望将同一个user的照片存放在一个文件夹中,以id号命名该照片。
具体方法见下文:
public static void downloadPhotos(String USERID, String OID, String urlString) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
System.out.println("Start to save photo.");
String downloadDir = "D:\\images\\"+USERID;
File downloadFilePath = new File(downloadDir);
if(downloadFilePath.exists() == false) // 如果该目录不存在,则创建之
downloadFilePath.mkdirs();
String FILENAME = downloadDir+"\\"+OID+".jpg"; //生成新的照片名
System.out.println(FILENAME);
OutputStream os = new FileOutputStream(FILENAME); // 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
参考:
http://hi.baidu.com/xuewei2099/item/f31c1e8634c967c7ee083db4