UnzipActivity
public class UnzipActivity extends Activity {
private static String TAG = "UnzipActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.unzip("/mnt/sdcard/20111107.zip");
}
private void unzip(String zipFilePath) {
Log.d(TAG, "Unzip: " + zipFilePath);
// 取得SD卡目錄,並以 App package 作為子目錄
File outDir = new File(Environment.getExternalStorageDirectory(),
this.getPackageName());
// 以下與一般 Java 程式作法無二
if (!outDir.exists()) {
// 要有 android.permission.WRITE_EXTERNAL_STORAGE 權限
outDir.mkdir();
}
if (!outDir.exists()) {
Log.e(TAG, "Can't create this path: " + outDir.getAbsolutePath());
return;
}
Log.d(TAG, "Ouput path: " + outDir.getAbsolutePath());
InputStream is = null;
BufferedInputStream bi = null;
BufferedOutputStream bo = null;
try {
ZipFile zipFile = new ZipFile(zipFilePath);
Enumeration<? extends ZipEntry> entryEnum = zipFile.entries();
ZipEntry entry;
File outFile;
// loop zip 檔案裡所有目錄與檔案
while (entryEnum.hasMoreElements()) {
entry = entryEnum.nextElement();
outFile = new File(outDir, entry.getName());
if (entry.isDirectory()) {
Log.d(TAG, "Add a folder: " + outFile.getAbsolutePath());
outFile.mkdir();
if (!outFile.exists()) {
Log.e(TAG,
"Can't create this path: "
+ outFile.getAbsolutePath());
return;
}
}
else {
Log.d(TAG, "Add a file: " + outFile.getAbsolutePath());
is = zipFile.getInputStream(entry);
bi = new BufferedInputStream(is);
bo = new BufferedOutputStream(new FileOutputStream(outFile));
int data = 0;
while ((data = bi.read()) != -1) {
bo.write(data);
}
bo.flush();
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (bi != null) {
try {
bi.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (bo != null) {
try {
bo.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
寫入檔案到 SD 卡需要授予權限: AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
為開發方便,可以透過 File Explorer 將壓縮檔案從電腦傳到 Android Emulator 裡。
相關文章


沒有留言:
張貼留言