カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

Zip形式圧縮ファイルを解凍する Android

この記事は最終更新日から1年以上経過しています。

Androidで、Zip形式の圧縮ファイルを解凍します。

インポート

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.BufferedOutputStream;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

必要な変数の宣言

ZipInputStream in = null;
String zipPath = null;
ZipEntry zipEntry;
int data;
String file_name;


解凍します

try {
	zipPath = Environment.getExternalStorageDirectory() + "/Sample/Example.zip";
	in = new ZipInputStream(new BufferedInputStream(
			new FileInputStream(zipPath)));
} catch (FileNotFoundException e) {
	e.printStackTrace();
	// "Zipファイルが見つかりませんでした。";
} catch (Exception e) {
	e.printStackTrace();
	// "Zipファイル取得時にエラーが発生しました。";
}

try {

	//Zip形式圧縮データ解凍
	while((zipEntry = in.getNextEntry()) != null) {

		//(int)zipEntry.getSize(); //取り出したファイルの容量

		// ファイルの名前を取得
		if(zipEntry.getName().matches(".*/.*"))
		{
			String[] fname = zipEntry.getName().split("/");
			file_name = fname[1];
		} else {
			file_name = zipEntry.getName();
		}

		// 解凍したファイルをアプリのファイル領域に書き込む
		BufferedOutputStream out = 
				new BufferedOutputStream(openFileOutput(file_name, MODE_PRIVATE));

		while((data = in.read()) != -1) {
			out.write(data);
		}

		out.close();
	}

} catch (IOException e) {
	e.printStackTrace();
} catch (Exception e) {
	try {
		in.close();
	} catch (IOException e1) {
		e1.printStackTrace();
	}
	e.printStackTrace();
}

try {
	in.close();
} catch (IOException e) {
	e.printStackTrace();
} catch (Exception e) {
	e.printStackTrace();
}
この記事がお役に立ちましたらシェアお願いします
6,573 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です