Java - 从zip文件获取特定文件夹和文件

时间:2015-04-15 02:26:30

标签: java android

所以我正在开发一个Android应用程序,而我想要做的就是让用户选择一个zip文件,它将其内容提取到apk中并为用户安装修改后的APK。现在,zip文件中的所有文件都必须位于zip文件的根目录才能工作,如果有目录而且我需要的文件不起作用。我试图让它扫描,例如'资产'文件夹,然后获取它所在的目录并复制该目录中的所有文件。我已经尝试首先提取文件并使用循环进行扫描,并且出于某种原因没有成功这样做,而且无论如何都是耗时的。如果你知道任何图书馆,或者可以指出我的方向很好!谢谢!

1 个答案:

答案 0 :(得分:1)

BTW你可以从zip文件夹中提取所有文件,如下所示。即

private String unpackZip(String path, String zipname) {
        String apkfilename = "";
        InputStream is;
        ZipInputStream zis;
        try {
            String filename;
            is = new FileInputStream(path + "/" + zipname);
            zis = new ZipInputStream(new BufferedInputStream(is));
            ZipEntry ze;
            byte[] buffer = new byte[1024];
            int count;
            while ((ze = zis.getNextEntry()) != null) {

                filename = ze.getName();

                // Need to create directories if not exists, or
                // it will generate an Exception...
                if (ze.isDirectory()) {
                    File fmd = new File(path + "/" + filename);
                    fmd.mkdirs();
                    continue;
                }
                // This condition is to only extract the apk file
                if (filename.endsWith(".apk")) {
                    apkfilename = filename;
                    FileOutputStream fout = new FileOutputStream(path + "/"
                            + filename);

                    while ((count = zis.read(buffer)) != -1) {
                        fout.write(buffer, 0, count);
                    }

                    fout.close();
                    zis.closeEntry();
                }
            }
            zis.close();
        } catch (IOException e) {
            e.printStackTrace();
            return apkfilename;
        }
        return apkfilename;
    }



  //To install the apk file call the method 
       String apkfilename=unpackZip(Environment.getExternalStorageDirectory()
            .getPath(), "temp.zip");


    try {
            File file = new File(Environment.getExternalStorageDirectory()
                    .getPath(), apkfilename);
            Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(
                    Uri.fromFile(file), "application/vnd.android.package-archive");
            startActivity(promptInstall);
        } catch (Exception e) {
            e.printStackTrace();
        }
//Also add the read write permission 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>