android文件复制及解压

提供两个自己写的方法,目标路径可以是SD卡,也可以是data/data私有文件夹。

/**
     * 解压Zip文件到目标路径
     * 
     * @param zipPath
     *            Zip文件路径
     * @param destdir
     *            目标路径
     * @throws IOException
     */
    public static void unZipFile(String zipPath, File destdir) throws IOException
    {
        if (destdir == null || !destdir.isDirectory())
        {
            throw new IOException("destdir is not valid");
        }
        if (!destdir.exists())
        {
            destdir.mkdirs();
        }
        ZipFile zipFile = new ZipFile(zipPath);
        Enumeration<?> e = zipFile.entries();
        while (e.hasMoreElements())
        {
            ZipEntry entry = (ZipEntry) e.nextElement();
            File file = new File(destdir, entry.getName());
            if (entry.isDirectory())
            {
                if (!file.exists())
                {
                    file.mkdirs();
                }
            } else
            {
                FileHelper.writeInputStreamToFile(zipFile.getInputStream(entry), file);
            }
        }
        zipFile.close();
    }
    /**
     * 复制assets内的指定文件/文件夹到目标路径
     * 
     * @param assetManager
     * @param path
     * @param destdir
     * @throws IOException
     */
    public static void copyAssetsFile(AssetManager assetManager, String path, File destdir) throws IOException
    {
        if (path == null)
        {
            throw new IOException("path is not valid");
        }
        if (!destdir.exists())
        {
            destdir.mkdirs();
        }
        if (path.indexOf('.') >= 0)
        {// 文件
            File file = new File(destdir, path);
            FileHelper.writeInputStreamToFile(assetManager.open(path), file);
            return;
        }
        String[] fileList = assetManager.list(path);
        for (String fileName : fileList)
        {
            String subPath = path + File.separator + fileName;
            if (fileName.indexOf('.') < 0)
            {// 文件夹,递归复制
                copyAssetsFile(assetManager, subPath, new File(destdir, fileName));
            } else
            {// 文件
                FileHelper.writeInputStreamToFile(assetManager.open(subPath), new File(destdir, fileName));
            }
        }
    }
    /**
     * write inputStream to a file
     * 
     * @param inputStream
     * @param file
     * @throws IOException
     */
    public static void writeInputStreamToFile(InputStream inputStream, File file) throws IOException
    {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        BufferedInputStream bi = new BufferedInputStream(inputStream);
        byte[] bytes = new byte[1024];
        int readCount = bi.read(bytes);
        while (readCount != -1)
        {
            bos.write(bytes, 0, readCount);
            readCount = bi.read(bytes);
        }
        bos.close();
    }

 

posted @ 2015-01-16 10:30  toronto  阅读(452)  评论(0编辑  收藏  举报