Android學習筆記————檔案下載

來源:互聯網
上載者:User

在進行應用開發的時候經常會涉及到檔案下載,並且儲存到指定的位置。在手機端則通常會選擇將下載的檔案儲存體到內建儲存或者外置的sd卡中。

要進行檔案下載,首先需要在AndroidManifest.xml檔案中申明需要的許可權:

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

分別是網路連接和外置空間讀寫的許可權。

進行檔案下載,主要涉及到java中輸入、輸出資料流的使用,整個過程也是非常簡單。

檔案下載可以細分為以下幾個步驟:

1、從對應檔案的url擷取相應的輸入資料流。

URL url = new URL("http://iphone.images.paojiao.cn/iphone/paper/20117/9/43198644/paojiao_a81d869d.jpg");//建立串連HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();//設定串連的一些屬性urlConnection.setRequestMethod("GET");urlConnection.setDoInput(true);urlConnection.connect();        inputStream = urlConnection.getInputStream();

2、擷取根據需要儲存的檔案路徑擷取輸出資料流。

File SDCardRoot = Environment.getExternalStorageDirectory();File file = new File(SDCardRoot + "/test/test_download.jpg");        fileOutput = new FileOutputStream(file);

需要說明的是Environment.getExternalStorageDirectory()得到的是內建儲存空間的路徑。

3、進行讀寫操作

byte[] buffer = new byte[1024];while ( (bufferLength = inputStream.read(buffer)) > 0 ) {fileOutput.write(buffer, 0, bufferLength);}fileOutput.flush();

4、讀寫完畢之後,關閉流。

try {inputStream.close();} catch (IOException e1) {e1.printStackTrace();}try {fileOutput.close();} catch (IOException e) {e.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.