1. 程式人生 > >Android下載網路資原始檔

Android下載網路資原始檔

直接上程式碼:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
new Thread(new Runnable() {
@Override
public void run() {
download()
; } }).start();
//下載具體操作
private boolean download() {
try {
URL url = new URL("http://file.chmsp.com.cn/colligate/file/00100000224821.pdf");
//開啟連線
URLConnection conn = url.openConnection();
//開啟輸入流
InputStream is = conn.getInputStream();
//獲得長度
int contentLength = conn.getContentLength();
Log.e("", "檔案長度 = " + contentLength
); //建立資料夾 MyDownLoad,在儲存卡下 String dirName = Environment.getExternalStorageDirectory() + "/"; //下載後的檔名 String fileName = dirName + "00100000224821.pdf"; File file1 = new File(fileName); if (file1.exists()) { Log.e("檔案-----", "檔案已經存在!"); return fileIsExists(fileName); } else { //建立位元組流 byte[] bs = new byte[1024]; int
len; OutputStream os = new FileOutputStream(fileName); //寫資料 while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } //完成後關閉流 Log.e("檔案不存在", "下載成功!"); os.close(); is.close(); } } catch (Exception e) { e.printStackTrace(); } return false; } //判斷檔案是否存在 public boolean fileIsExists(String strFile) { try { File f = new File(strFile); if (!f.exists()) { return false; } } catch (Exception e) { return false; } return true; }