java根據下載地址下載檔案到本地
阿新 • • 發佈:2019-01-27
根據一個下載地址現在到本地路徑,直接上乾貨。
fileUrl:需要下載的地址,fileLocal:本地路徑(需要加上檔案的字尾名)
/**
* TODO 下載檔案到本地* @author nadim
* @date Sep 11, 2015 11:45:31 AM
* @param fileUrl 遠端地址
* @param fileLocal 本地路徑
* @throws Exception
*/
public boolean downloadFile(String fileUrl,String fileLocal) throws Exception {
boolean flag=false;
URL url = new URL(fileUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setConnectTimeout(6000);
urlCon.setReadTimeout(6000);
int code = urlCon.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("檔案讀取失敗");
}
//讀檔案流
DataInputStream in = new DataInputStream(urlCon.getInputStream());
DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
byte[] buffer = new byte[2048];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
try {
if(out!=null) {
out.close();
}
if(in!=null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
flag=true;
return flag;
}