您的位置:首页 > 理论基础 > 计算机网络

关于Java中Http下载的一些整理

2011-07-21 12:15 253 查看
/**
* 下载小图
* @param img
*/
public String download(String file){
DataInputStream is = null;
DataOutputStream os = null;
String p = "";
HttpURLConnection con = null;
try {
URL url = new URL(file);
con = (HttpURLConnection) url.openConnection();
URL path = Thread.currentThread().getContextClassLoader().getResource("");
p = path.getPath();
String[] strs = url.getFile().split("/");
p = p.replace("WEB-INF/classes/", "") + "images/" + strs[strs.length-1];
p = p.substring(1);
File img11 = new File(p);
if(!img11.exists()){
img11.createNewFile();
}
is = new DataInputStream(con.getInputStream());
os = new DataOutputStream(new FileOutputStream(p));
byte[] buffer = new byte[51200];
int count = 0;
while(((count = is.read(buffer)) > 0)){
os.write(buffer, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
is.close();
os.close();
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return p;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: