2014年1月14日

Android zip解壓縮後,讀取資料夾下的檔案清單做驗證

這兩天剛好寫到需要從網路下載壓縮檔案存在手機裡,並把zip壓縮檔解壓縮。 因為會儲到SD Card,所以先要在AndroidManifest.xml 加入 "android.permission.WRITEEXTERNALSTORAGE"權限。

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

以下為解壓縮的程式碼:

String srcPath = Environment.getExternalStorageDirectory().toString() + "/download/data.zip";
String destPath = Environment.getExternalStorageDirectory().toString() + "/download/data/";

BufferedOutputStream bufferedOutputStream = null;
FileInputStream fileInputStream;
try {
    fileInputStream = new FileInputStream(srcPath);
    ZipInputStream zipInputStream = new ZipInputStream(
                new BufferedInputStream(fileInputStream));

    ZipEntry zipEntry;

     //讀出壓縮檔裡的檔案
     while ((zipEntry = zipInputStream.getNextEntry()) != null ) {

         String zipEntryName = zipEntry.getName();

         File file = new File(destPath + zipEntryName);

          if (!file.exists()) {

                if (zipEntry.isDirectory()) {
                    file.mkdirs();//如果是目錄先建立
               } else {
                    //檔案則另存

                    byte buffer[] = new byte[ 1024];
                    FileOutputStream fileOutputStream = new FileOutputStream(
                               file);
                    bufferedOutputStream = new BufferedOutputStream(
                               fileOutputStream, 1024);

                     int count;
                     while ((count = zipInputStream.read(buffer, 0,
                                1024)) != -1) {
                         bufferedOutputStream.write(buffer, 0, count);
                    }
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
               }
         }
    }

    zipInputStream.close();

    //驗證檔存不存在
    checkFile();

} catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
     // TODO Auto-generated catch block
    e.printStackTrace();
}

以下的程式碼是用來讀取資料夾路徑裡的檔案清單,剛好可以拿來驗證解壓縮檔案是否成功。

private void checkFile(){
    String filepath = Environment.getExternalStorageDirectory().toString()+"/download/data/";
    Log.d("Filepath", filepath);
    File file = new File(filepath);

    File files[] = file.listFiles();
    Log.d("Files", "Size: "+ files.length);
    for (int i=0; i < files.length; i++){
        Log.d("Files", "FileName:" + files[i].getName());
    }
}

filepath 是資料夾路徑,file.listFiles()是取出檔案清單。