extract Apk files - Java File Path IO

Java examples for File Path IO:File Operation

Description

extract Apk files

Demo Code


import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Main{
    public static void main(String[] argv) throws Exception{
        String apkPath = "java2s.com";
        System.out.println(extractApks(apkPath));
    }/* w w w  .  j  a va  2  s. co  m*/
    public static int BUFFER = 2048;
    public synchronized static List<String> extractApks(String apkPath) {
        List<String> ret = new ArrayList<String>();
        try {
            ZipFile zip = new ZipFile(apkPath);
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (entry.getName().endsWith(".apk")) {
                    // Get a new tmp file
                    String tmpFilePath = FileUtil.getTempFile("apktmp_",
                            ".apk");
                    FileOutputStream fos = new FileOutputStream(tmpFilePath);
                    BufferedInputStream is = new BufferedInputStream(
                            zip.getInputStream(entry));
                    // Get it out of the box
                    int count = 0;
                    byte[] buf = new byte[BUFFER];
                    count = is.read(buf, 0, BUFFER);
                    while ((count = is.read(buf, 0, BUFFER)) != -1) {
                        fos.write(buf, 0, count);
                    }
                    fos.flush();
                    fos.close();

                    // If the zip contains AndroidManifest.xml, basically it's
                    // an apk
                    JarFile jar = new JarFile(tmpFilePath);
                    if (jar.getEntry("AndroidManifest.xml") != null)
                        ret.add(tmpFilePath);
                    jar.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }
}

Related Tutorials