十五、从互联网获取图片且保存到指定目录

package com.ljq.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.junit.Test;

/**
* 从互联网获取图片且保存到指定目录里
*
*
@author jiqinlin
*
*/
public class InternetTest {

@SuppressWarnings(
"static-access")
@Test
public void getImg() throws Exception {
String urlPath
= "http://i0.itc.cn/20101116/62d_67fd2b2a_207d_4de2_a4f9_fb93cc8da492_0.jpg";
URL url
= new URL(urlPath);
HttpURLConnection conn
= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(
6*1000); // 注意要设置超时,设置时间不要超过10秒,避免被android系统回收
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream inSream
= conn.getInputStream();
//把图片保存到项目的根目录
new InternetTest().readAsFile(inSream, new File("sohu.jpg"));
}

public static void readAsFile(InputStream inSream, File file) throws Exception{
FileOutputStream outStream
= new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer,
0, len);
}
outStream.close();
inSream.close();
}

}
posted on 2011-05-31 15:15  Ruthless  阅读(2038)  评论(0编辑  收藏  举报