檔案下載

1 篇文章 / 0 new
author
檔案下載
從網路下載檔案的方法
private void fileDownload(String url) throws Exception {
    String TAG = "fileDownload";
    if (!URLUtil.isNetworkUrl(url)) {
        Log.d(TAG, "網址錯誤");
    } else {
        // 建立連線
        URLConnection conn = (new URL(url)).openConnection();
        conn.connect();
        // 下載檔案
        InputStream src = conn.getInputStream();
        if (src == null) {
            throw new RuntimeException("stream is null");
        }
        // 建立暫存檔案,命名規則為 fileName+亂數+fileExName, 且自動指向SDCard
        File tempFile = File.createTempFile(fileName, fileExName);
        Log.d(TAG, "暫存檔案路徑:" + tempFile.getAbsolutePath());
        // 輸出目標檔
        FileOutputStream tar = new FileOutputStream(tempFile);
        // 資料輸出
        byte buf[] = new byte[128];
        int inxRead;
        do {
            inxRead = src.read(buf);
            if (inxRead <= 0) break;
            tar.write(buf, 0, inxRead);
        } while (true);
        try {
            src.close();
        } catch (Exception e) {
            Log.e(TAG, "error:" + e.getMessage(), e);
        }
    }
}
Free Web Hosting