檔案下載(java) android

來源:互聯網
上載者:User
// /////////////////////////////////下載檔案功能如下//////////////////////////////////private void DownFile(String urlString){/* * 串連到伺服器 */double FileLength = 0;double DownedFileLength = 0;InputStream inputStream = null;URLConnection connection = null;OutputStream outputStream = null;try{URL url = new URL(urlString);connection = url.openConnection();if (connection.getReadTimeout() == 5){Log.i("---------->", "當前網路有問題");}inputStream = connection.getInputStream();} catch (MalformedURLException e1){// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}/* * 檔案的儲存路徑和和檔案名稱其中Nobody.mp3是在手機SD卡上要儲存的路徑,如果不存在則建立 */String savePAth = Environment.getExternalStorageDirectory()+ "/lzmDownload";File file1 = new File(savePAth);if (!file1.exists()){file1.mkdir();}String savePathString = Environment.getExternalStorageDirectory()+ "/lzmDownload/" + "test.png";File file = new File(savePathString);try{L.l("======================newFile:" + file.createNewFile());file.createNewFile();L.l("======================newFile:" + file.createNewFile());} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}/* * 向SD卡中寫入檔案,用Handle傳遞線程 */Message message = new Message();try{outputStream = new FileOutputStream(file);byte[] buffer = new byte[1024 * 4];FileLength = connection.getContentLength();L.l("==================FileSize:" + FileLength);message.what = 0;handler.sendMessage(message);while (DownedFileLength < FileLength){outputStream.write(buffer);DownedFileLength += inputStream.read(buffer);i = (int) (((double) DownedFileLength / FileLength) * 100);Message message1 = new Message();message1.what = 1; // downloading... the filehandler.sendMessage(message1);}Message message2 = new Message(); // finish the downloadmessage2.what = 2;handler.sendMessage(message2);} catch (FileNotFoundException e){// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}}// ///////////////////如上為一個下載類/////////////////////////////////////////////

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.