/**
* 保存指定URL的源文件到指定路径下
*
* @param srcUrl 要下载文件的绝对路径url
* @param filePath 文件要保存的路径
*/
public static synchronized void downloadFileByUrl(String srcUrl,String filePath) {
System.out.print("下载"+srcUrl);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(srcUrl);
HttpResponse response;
FileOutputStream out = null;
try {
String[] array = srcUrl.split("\\/");
String[] fname = array[array.length-1].split("\\.");
String fileName="",extname="";
if(fname.length == 2){
fileName = fname[0];
extname = fname[1];
}
File wdFile = new File(filePath + fileName+"."+extname);
//文件已存在
if(wdFile.exists()){
fileName += RandomID.GenTradeId();
wdFile = new File(filePath + fileName+"."+extname);
}
out = new FileOutputStream(wdFile);
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("............. 结束");
}
使用httpclient下载文件
最新推荐文章于 2021-09-15 14:53:17 发布