在進行應用開發的時候經常會涉及到檔案下載,並且儲存到指定的位置。在手機端則通常會選擇將下載的檔案儲存體到內建儲存或者外置的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();}
這樣,簡單的檔案下載功能便實現了,當然複雜的功能,如:斷點續傳,多線程下載等,後續再進行分析。