天天看點

Android程式解壓縮zip檔案,并加載顯示解壓後的檔案内容

剛做了個demo用于解壓縮本地zip檔案,并用webview顯示其中的一個html檔案,直接上代碼,需要的朋友可以看看

public class ZipActivity extends Activity { private static final String TAG = "HelloXmlActivity"; private WebView mWebView; private static LinkedHashMap<String, String> widgetInfoMap = new LinkedHashMap<String, String>(); //http://blog.csdn.net/com360/article/details/6618086 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String zipfile = "/sdcard/abc.zip"; try { unzip(zipfile, "/sdcard/");//yangguangfu/wujiali/ } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } mWebView=(WebView)findViewById(R.id.web); mWebView.loadUrl("file:///sdcard/abc/aaa.html");//此處加載解壓後的html内容 } private void unzip(String zipFileName, String outputDirectory) throws Exception { ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName)); ZipEntry z; String name = ""; String extractedFile = ""; int counter = 0; while ((z = in.getNextEntry()) != null) { name = z.getName(); Log.d(TAG, "unzipping file: " + name); if (z.isDirectory()) { Log.d(TAG, name + "is a folder"); // get the folder name of the widget name = name.substring(0, name.length() - 1); File folder = new File(outputDirectory + File.separator + name); folder.mkdirs(); if (counter == 0) { extractedFile = folder.toString(); } counter++; Log.d(TAG, "mkdir " + outputDirectory + File.separator + name); } else { Log.d(TAG, name + "is a normal file"); File file = new File(outputDirectory + File.separator + name); file.createNewFile(); // get the output stream of the file FileOutputStream out = new FileOutputStream(file); int ch; byte[] buffer = new byte[1024]; // read (ch) bytes into buffer while ((ch = in.read(buffer)) != -1) { // write (ch) byte from buffer at the position 0 out.write(buffer, 0, ch); out.flush(); } out.close(); } } in.close(); } }

其中我的abc.zip檔案是放在sdcard中的,裡面有2個檔案,解壓後生成一個abc檔案夾,檔案夾下是解壓縮後的2個檔案,我用一個webview直接指定加載了解壓後的一個html檔案,做的比較粗糙,省去了檔案存在判斷,掃描檔案名、檔案類型,main.xml檔案也很簡單,通過上面代碼應該可以看出其中的控件,這裡不再寫xml布局檔案了。

更多資訊可參考下面文章:

加載html與js:

http://blog.csdn.net/com360/article/details/6618086

解壓縮zip檔案

http://www.oschina.net/code/snippet_4873_4142