工作很快樂,學習很簡單,愛編程,愛技術。
一一一一 想成爲架構師的小白
用Java代碼實現:根據指定URL將文件下載到指定目標位置。
package test1;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class FileDown {
/**
* 說明:根據指定URL將文件下載到指定目標位置
*
* @param urlPath
* 下載路徑
* @param downloadDir
* 文件存放目錄
* @return 返回下載文件
*/
@SuppressWarnings("finally")
public static File downloadFile(String urlPath, String downloadDir) {
File file = null;
try {
// 統一資源
URL url = new URL(urlPath);
// 連接類的父類,抽象類
URLConnection urlConnection = url.openConnection();
// http的連接類
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//設置超時
httpURLConnection.setConnectTimeout(1000*5);
//設置請求方式,默認是GET
httpURLConnection.setRequestMethod("POST");
// 設置字符編碼
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打開到此 URL引用的資源的通信鏈接(如果尚未建立這樣的連接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 控制檯打印文件大小
System.out.println("您要下載的文件大小爲:" + fileLength / (1024 * 1024) + "MB");
// 建立鏈接從請求中獲取數據
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
// 指定文件名稱(有需求可以自定義)
String fileFullName = "aaa.apk";
// 指定存放位置(有需求可以自定義)
String path = downloadDir + File.separatorChar + fileFullName;
file = new File(path);
// 校驗文件夾目錄是否存在,不存在就創建一個目錄
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[2048];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 控制檯打印文件下載的百分比情況
System.out.println("下載了-------> " + len * 100 / fileLength + "%\n");
}
// 關閉資源
bin.close();
out.close();
System.out.println("文件下載成功!");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("文件下載失敗!");
} finally {
return file;
}
}
/**
* 測試
*
* @param args
*/
public static void main(String[] args) {
// 指定資源地址,下載文件測試
downloadFile("http://count.liqucn.com/d.php?id=22709&urlos=android&from_type=web", "B:/myFiles/");
}
}
共同學習,共同進步,工作很快樂,學習很簡單
附:
阿里巴巴Java開發手冊(詳盡版),新增16條設計規約,跟着元老們一起學習Java規範,走向人生巔峯 點擊打開鏈接
阿里開源的 IDE 代碼規約檢測插件(最新版),阿里IT大佬們極力推薦 點擊打開鏈接
*注 :以上文件都爲及時更新。