歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android程序解壓縮zip文件並加載顯示解壓後的文件內容

Android程序解壓縮zip文件並加載顯示解壓後的文件內容

日期:2017/3/1 10:36:14   编辑:Linux編程

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

  1. public class ZipActivity extends Activity {
  2. private static final String TAG = "HelloXmlActivity";
  3. private WebView mWebView;
  4. private static LinkedHashMap<String, String> widgetInfoMap = new LinkedHashMap<String, String>();
  5. //http://blog.csdn.net/com360/article/details/6618086
  6. /** Called when the activity is first created. */
  7. @Override
  8. public void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.main);
  11. String zipfile = "/sdcard/abc.zip";
  12. try {
  13. unzip(zipfile, "/sdcard/");//yangguangfu/wujiali/
  14. } catch (Exception e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }
  18. mWebView=(WebView)findViewById(R.id.web);
  19. mWebView.loadUrl("file:///sdcard/abc/aaa.html");//此處加載解壓後的html內容
  20. }
  21. /*
  22. * 這個是解壓ZIP格式文件的方法
  23. *
  24. * @zipFileName:是傳進來你要解壓的文件路徑,包括文件的名字;
  25. *
  26. * @outputDirectory:選擇你要保存的路勁;
  27. *
  28. */
  29. private void unzip(String zipFileName, String outputDirectory)
  30. throws Exception {
  31. ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
  32. ZipEntry z;
  33. String name = "";
  34. String extractedFile = "";
  35. int counter = 0;
  36. while ((z = in.getNextEntry()) != null) {
  37. name = z.getName();
  38. Log.d(TAG, "unzipping file: " + name);
  39. if (z.isDirectory()) {
  40. Log.d(TAG, name + "is a folder");
  41. // get the folder name of the widget
  42. name = name.substring(0, name.length() - 1);
  43. File folder = new File(outputDirectory + File.separator + name);
  44. folder.mkdirs();
  45. if (counter == 0) {
  46. extractedFile = folder.toString();
  47. }
  48. counter++;
  49. Log.d(TAG, "mkdir " + outputDirectory + File.separator + name);
  50. } else {
  51. Log.d(TAG, name + "is a normal file");
  52. File file = new File(outputDirectory + File.separator + name);
  53. file.createNewFile();
  54. // get the output stream of the file
  55. FileOutputStream out = new FileOutputStream(file);
  56. int ch;
  57. byte[] buffer = new byte[1024];
  58. // read (ch) bytes into buffer
  59. while ((ch = in.read(buffer)) != -1) {
  60. // write (ch) byte from buffer at the position 0
  61. out.write(buffer, 0, ch);
  62. out.flush();
  63. }
  64. out.close();
  65. }
  66. }
  67. in.close();
  68. }
  69. }

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

更多信息可參考下面文章:

加載html與js: http://www.linuxidc.com/Linux/2012-01/52718.htm

解壓縮zip文件: http://www.linuxidc.com/Linux/2012-01/52719.htm

Copyright © Linux教程網 All Rights Reserved