android文件或文件夹压缩

来源:互联网 发布:洛阳 知乎 编辑:程序博客网 时间:2024/05/23 16:43
private static final int BUFFER = 1024 * 1024;/** * 压缩目录 *  * @param File *            dir * @param ZipOutputStream *            out * @param String *            basedir */private void compress2Directory(File dir, ZipOutputStream out,String basedir) {if (!dir.exists())return;File[] files = dir.listFiles();if(files!=null && files.length !=0){for (int i = 0; i < files.length; i++) {compress(files[i], out, basedir + dir.getName() + "/");}}}/** * 压缩文件 *  * @param File *            file * @param ZipOutputStream *            out * @param String *            basedir */private void compress2File(File file, ZipOutputStream out, String basedir) {if (!file.exists()) {return;}BufferedInputStream bis = null;try {bis = new BufferedInputStream(new FileInputStream(file));ZipEntry entry = new ZipEntry(basedir + file.getName());out.putNextEntry(entry);int count;byte data[] = new byte[BUFFER];while ((count = bis.read(data, 0, BUFFER)) != -1) {out.write(data, 0, count);}} catch (Exception e) {Write.debug(""+e.getMessage());}finally {try {bis.close();} catch (IOException e) {Write.debug(""+e.getMessage());}}}public void compress(File file, ZipOutputStream out, String basedir) {if (file.isFile()) {this.compress2File(file, out, basedir);} else {this.compress2Directory(file, out, basedir);}}

0 0