Android(安卓)zip文件压缩解压
16lz
2021-01-25
阅读更多
Android zip文件压缩解压
Android项目中需要将一些信息进行收集再进行压缩,最后将压缩文件上传到服务器中,以下代码实现此功能,并支持中文文件名
package com.example.androidzip.tools;import java.io.File;import java.util.ArrayList;import java.util.LinkedList;/** * 文件夹遍历 * @author miaowei * */public class DirTraversal {//no recursion public static LinkedListlistLinkedFiles(String strPath) { LinkedList list = new LinkedList (); File dir = new File(strPath); File file[] = dir.listFiles(); for (int i = 0; i < file.length; i++) { /*if (file[i].isDirectory()){ list.add(file[i]); }else{ System.out.println(file[i].getAbsolutePath()); }*/ list.add(file[i]); } /*File tmp; while (!list.isEmpty()) { tmp = (File) list.removeFirst(); if (tmp.isDirectory()) { file = tmp.listFiles(); if (file == null) continue; for (int i = 0; i < file.length; i++) { if (file[i].isDirectory()) list.add(file[i]); else System.out.println(file[i].getAbsolutePath()); } } else { System.out.println(tmp.getAbsolutePath()); } }*/ return list; } //recursion public static ArrayList listFiles(String strPath) { return refreshFileList(strPath); } public static ArrayList refreshFileList(String strPath) { ArrayList filelist = new ArrayList (); File dir = new File(strPath); File[] files = dir.listFiles(); if (files == null) return null; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { refreshFileList(files[i].getAbsolutePath()); } else { if(files[i].getName().toLowerCase().endsWith("zip")){ filelist.add(files[i]); } } } return filelist; } public static ArrayList arrayListFiles(String strPath){ ArrayList filelist = new ArrayList (); File dir = new File(strPath); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { filelist.add(files[i].getAbsoluteFile());} return filelist; } //-----4.0读取文件的报 open failed: ENOENT (No such file or directory) /** * 1\可先创建文件的路径 * @param filePath */public static void makeRootDirectory(String filePath) {File file = null;try {file = new File(filePath);if (!file.exists()) {file.mkdir();}} catch (Exception e) {e.printStackTrace();}} /** * 2\然后在创建文件名就不会在报该错误 * @param filePath * @param fileName * @return */public static File getFilePath(String filePath, String fileName) {File file = null;makeRootDirectory(filePath);try {file = new File(filePath + fileName);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return file;}}
package com.example.androidzip.tools;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Collection;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipException;import java.util.zip.ZipFile;import java.util.zip.ZipOutputStream;/** * Java utils 实现的Zip工具 * @author miaowei * */public class ZipUtils {private static final int BUFF_SIZE = 1024 * 1024; // 1M Byte /** * 批量压缩文件(夹) * * @param resFileList 要压缩的文件(夹)列表 * @param zipFile 生成的压缩文件 * @throws IOException 当压缩过程出错时抛出 */ public static void zipFiles(CollectionresFileList, File zipFile) throws IOException { ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE)); for (File resFile : resFileList) { zipFile(resFile, zipout, ""); } zipout.close(); } /** * 批量压缩文件(夹) * * @param resFileList 要压缩的文件(夹)列表 * @param zipFile 生成的压缩文件 * @param comment 压缩文件的注释 * @throws IOException 当压缩过程出错时抛出 */ public static void zipFiles(Collection resFileList, File zipFile, String comment) throws IOException { ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream( zipFile), BUFF_SIZE)); for (File resFile : resFileList) { zipFile(resFile, zipout, ""); } zipout.setComment(comment); zipout.close(); } /** * 解压缩一个文件 * * @param zipFile 压缩文件 * @param folderPath 解压缩的目标目录 * @throws IOException 当解压缩过程出错时抛出 */ public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException { File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdirs(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry)entries.nextElement()); if (entry.isDirectory()) { continue;} InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = new String(str.getBytes(), "utf-8"); File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); } } /** * 解压文件名包含传入文字的文件 * * @param zipFile 压缩文件 * @param folderPath 目标文件夹 * @param nameContains 传入的文件匹配名 * @throws ZipException 压缩格式有误时抛出 * @throws IOException IO错误时抛出 */ public static ArrayList upZipSelectedFile(File zipFile, String folderPath, String nameContains) throws ZipException, IOException { ArrayList fileList = new ArrayList (); File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdir(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry)entries.nextElement()); if (entry.getName().contains(nameContains)) { InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = new String(str.getBytes("utf-8"), "gbk"); // str.getBytes("GB2312"),"8859_1" 输出 // str.getBytes("8859_1"),"GB2312" 输入 File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); fileList.add(desFile); } } return fileList; } /** * 获得压缩文件内文件列表 * * @param zipFile 压缩文件 * @return 压缩文件内文件名称 * @throws ZipException 压缩文件格式有误时抛出 * @throws IOException 当解压缩过程出错时抛出 */ public static ArrayList getEntriesNames(File zipFile) throws ZipException, IOException { ArrayList entryNames = new ArrayList (); Enumeration<?> entries = getEntriesEnumeration(zipFile); while (entries.hasMoreElements()) { ZipEntry entry = ((ZipEntry)entries.nextElement()); entryNames.add(new String(getEntryName(entry).getBytes("GB2312"), "8859_1")); } return entryNames; } /** * 获得压缩文件内压缩文件对象以取得其属性 * * @param zipFile 压缩文件 * @return 返回一个压缩文件列表 * @throws ZipException 压缩文件格式有误时抛出 * @throws IOException IO操作有误时抛出 */ public static Enumeration<?> getEntriesEnumeration(File zipFile) throws ZipException, IOException { ZipFile zf = new ZipFile(zipFile); return zf.entries(); } /** * 取得压缩文件对象的注释 * * @param entry 压缩文件对象 * @return 压缩文件对象的注释 * @throws UnsupportedEncodingException */ public static String getEntryComment(ZipEntry entry) throws UnsupportedEncodingException { return new String(entry.getComment().getBytes("GB2312"), "8859_1"); } /** * 取得压缩文件对象的名称 * * @param entry 压缩文件对象 * @return 压缩文件对象的名称 * @throws UnsupportedEncodingException */ public static String getEntryName(ZipEntry entry) throws UnsupportedEncodingException { return new String(entry.getName().getBytes("GB2312"), "8859_1"); } /** * 压缩文件 * * @param resFile 需要压缩的文件(夹) * @param zipout 压缩的目的文件 * @param rootpath 压缩的文件路径 * @throws FileNotFoundException 找不到文件时抛出 * @throws IOException 当压缩过程出错时抛出 */ private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException { rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName(); rootpath = new String(rootpath.getBytes(), "utf-8"); if (resFile.isDirectory()) { File[] fileList = resFile.listFiles(); for (File file : fileList) { zipFile(file, zipout, rootpath); } } else { byte buffer[] = new byte[BUFF_SIZE]; BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile), BUFF_SIZE); zipout.putNextEntry(new ZipEntry(rootpath)); int realLength; while ((realLength = in.read(buffer)) != -1) { zipout.write(buffer, 0, realLength); } in.close(); zipout.flush(); zipout.closeEntry(); } } //第二种实现public static void zip(String src, String dest) throws IOException {// 提供了一个数据项压缩成一个ZIP归档输出流ZipOutputStream out = null;try {//DirTraversal.makeRootDirectory(dest);//File outFile = DirTraversal.getFilePath(dest,"cache.zip");File outFile = new File(dest);// 源文件或者目录File fileOrDirectory = new File(src);// 压缩文件路径out = new ZipOutputStream(new FileOutputStream(outFile));// 如果此文件是一个文件,否则为false。if (fileOrDirectory.isFile()) {zipFileOrDirectory(out, fileOrDirectory, "");} else {// 返回一个文件或空阵列。File[] entries = fileOrDirectory.listFiles();for (int i = 0; i < entries.length; i++) {// 递归压缩,更新curPathszipFileOrDirectory(out, entries[i], "");}}} catch (IOException ex) {ex.printStackTrace();} finally {// 关闭输出流if (out != null) {try {out.close();} catch (IOException ex) {ex.printStackTrace();}}}}private static void zipFileOrDirectory(ZipOutputStream out,File fileOrDirectory, String curPath) throws IOException {// 从文件中读取字节的输入流FileInputStream in = null;try {// 如果此文件是一个目录,否则返回false。if (!fileOrDirectory.isDirectory()) {// 压缩文件byte[] buffer = new byte[4096];int bytes_read;in = new FileInputStream(fileOrDirectory);// 实例代表一个条目内的ZIP归档ZipEntry entry = new ZipEntry(curPath+ fileOrDirectory.getName());// 条目的信息写入底层流out.putNextEntry(entry);while ((bytes_read = in.read(buffer)) != -1) {out.write(buffer, 0, bytes_read);}out.closeEntry();} else {// 压缩目录File[] entries = fileOrDirectory.listFiles();for (int i = 0; i < entries.length; i++) {// 递归压缩,更新curPathszipFileOrDirectory(out, entries[i], curPath+ fileOrDirectory.getName() + "/");}}} catch (IOException ex) {ex.printStackTrace();// throw ex;} finally {if (in != null) {try {in.close();} catch (IOException ex) {ex.printStackTrace();}}}}@SuppressWarnings("unchecked")public static void unzip(String zipFileName, String outputDirectory)throws IOException {ZipFile zipFile = null;try {zipFile = new ZipFile(zipFileName);Enumeration e = zipFile.entries();ZipEntry zipEntry = null;File dest = new File(outputDirectory);dest.mkdirs();while (e.hasMoreElements()) {zipEntry = (ZipEntry) e.nextElement();String entryName = zipEntry.getName();InputStream in = null;FileOutputStream out = null;try {if (zipEntry.isDirectory()) {String name = zipEntry.getName();name = name.substring(0, name.length() - 1);File f = new File(outputDirectory + File.separator+ name);f.mkdirs();} else {int index = entryName.lastIndexOf("\\");if (index != -1) {File df = new File(outputDirectory + File.separator+ entryName.substring(0, index));df.mkdirs();}index = entryName.lastIndexOf("/");if (index != -1) {File df = new File(outputDirectory + File.separator+ entryName.substring(0, index));df.mkdirs();}File f = new File(outputDirectory + File.separator+ zipEntry.getName());// f.createNewFile();in = zipFile.getInputStream(zipEntry);out = new FileOutputStream(f);int c;byte[] by = new byte[1024];while ((c = in.read(by)) != -1) {out.write(by, 0, c);}out.flush();}} catch (IOException ex) {ex.printStackTrace();throw new IOException("解压失败:" + ex.toString());} finally {if (in != null) {try {in.close();} catch (IOException ex) {}}if (out != null) {try {out.close();} catch (IOException ex) {}}}}} catch (IOException ex) {ex.printStackTrace();throw new IOException("解压失败:" + ex.toString());} finally {if (zipFile != null) {try {zipFile.close();} catch (IOException ex) {}}}}}
package com.example.androidzip;import java.io.File;import java.io.IOException;import java.lang.reflect.Field;import java.util.LinkedList;import java.util.zip.ZipException;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import com.example.androidzip.tools.DirTraversal;import com.example.androidzip.tools.ZipUtils;/** * Android zip文件压缩解压缩 * @author miaowei * */public class MainActivity extends Activity {/** * 压缩 */private Button btn_zip;/** * 解压 */private Button btn_unzip;String pathString = Environment.getExternalStorageDirectory().getAbsolutePath();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn_unzip = (Button)findViewById(R.id.btn_unzip);btn_zip = (Button)findViewById(R.id.btn_zip);btn_zip.setOnClickListener(onClickListener);btn_unzip.setOnClickListener(onClickListener);}private OnClickListener onClickListener = new OnClickListener(){@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btn_zip:try {//测试数据,注意更换目录LinkedListfiles = DirTraversal.listLinkedFiles(pathString+"/Android/data/com.mapbar.info.collection/files/cache");File file = DirTraversal.getFilePath(pathString+"/Android/data/com.mapbar.info.collection/files/", "cache.zip");ZipUtils.zipFiles(files, file);//第二种实现//ZipUtils.zip(pathString+"/Android/data/com.mapbar.info.collection/files/cache", pathString+"/Android/data/com.mapbar.info.collection/files/cache.zip");//ZipUtils.unzip(pathString+"/Android/data/com.mapbar.info.collection/files/cache.zip", pathString+"/Android/data/com.mapbar.info.collection/files/cache");} catch (IOException e) {e.printStackTrace();}break;case R.id.btn_unzip:File file = DirTraversal.getFilePath(pathString+"/Android/data/com.mapbar.info.collection/files/", "cache.zip");try {ZipUtils.upZipFile(file, pathString+"/Android/data/com.mapbar.info.collection/files/cachezip");} catch (ZipException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}break;default:break;}}};}
以下为处理乱码转换字符串的编码
/** * 转换字符串的编码 */ public class ChangeCharset { /** 7位ASCII字符,也叫作ISO646-US、Unicode字符集的基本拉丁块 */ public static final String US_ASCII = "US-ASCII"; /** ISO 拉丁字母表 No.1,也叫作 ISO-LATIN-1 */ public static final String ISO_8859_1 = "ISO-8859-1"; /** 8 位 UCS 转换格式 */ public static final String UTF_8 = "UTF-8"; /** 16 位 UCS 转换格式,Big Endian(最低地址存放高位字节)字节顺序 */ public static final String UTF_16BE = "UTF-16BE"; /** 16 位 UCS 转换格式,Little-endian(最高地址存放低位字节)字节顺序 */ public static final String UTF_16LE = "UTF-16LE"; /** 16 位 UCS 转换格式,字节顺序由可选的字节顺序标记来标识 */ public static final String UTF_16 = "UTF-16"; /** 中文超大字符集 */ public static final String GBK = "GBK"; /** * 将字符编码转换成US-ASCII码 */ public String toASCII(String str) throws UnsupportedEncodingException { return this.changeCharset(str, US_ASCII); } /** * 将字符编码转换成ISO-8859-1码 */ public String toISO_8859_1(String str) throws UnsupportedEncodingException { return this.changeCharset(str, ISO_8859_1); } /** * 将字符编码转换成UTF-8码 */ public String toUTF_8(String str) throws UnsupportedEncodingException { return this.changeCharset(str, UTF_8); } /** * 将字符编码转换成UTF-16BE码 */ public String toUTF_16BE(String str) throws UnsupportedEncodingException { return this.changeCharset(str, UTF_16BE); } /** * 将字符编码转换成UTF-16LE码 */ public String toUTF_16LE(String str) throws UnsupportedEncodingException { return this.changeCharset(str, UTF_16LE); } /** * 将字符编码转换成UTF-16码 */ public String toUTF_16(String str) throws UnsupportedEncodingException { return this.changeCharset(str, UTF_16); } /** * 将字符编码转换成GBK码 */ public String toGBK(String str) throws UnsupportedEncodingException { return this.changeCharset(str, GBK); } /** * 字符串编码转换的实现方法 * @param str 待转换编码的字符串 * @param newCharset 目标编码 * @return * @throws UnsupportedEncodingException */ public String changeCharset(String str, String newCharset) throws UnsupportedEncodingException { if (str != null) { //用默认字符编码解码字符串。 byte[] bs = str.getBytes(); //用新的字符编码生成字符串 return new String(bs, newCharset); } return null; } /** * 字符串编码转换的实现方法 * @param str 待转换编码的字符串 * @param oldCharset 原编码 * @param newCharset 目标编码 * @return * @throws UnsupportedEncodingException */ public String changeCharset(String str, String oldCharset, String newCharset) throws UnsupportedEncodingException { if (str != null) { //用旧的字符编码解码字符串。解码可能会出现异常。 byte[] bs = str.getBytes(oldCharset); //用新的字符编码生成字符串 return new String(bs, newCharset); } return null; } public static void main(String[] args) throws UnsupportedEncodingException { ChangeCharset test = new ChangeCharset(); String str = "This is a 中文的 String!"; System.out.println("str: " + str); String gbk = test.toGBK(str); System.out.println("转换成GBK码: " + gbk); System.out.println(); String ascii = test.toASCII(str); System.out.println("转换成US-ASCII码: " + ascii); gbk = test.changeCharset(ascii,ChangeCharset.US_ASCII, ChangeCharset.GBK); System.out.println("再把ASCII码的字符串转换成GBK码: " + gbk); System.out.println(); String iso88591 = test.toISO_8859_1(str); System.out.println("转换成ISO-8859-1码: " + iso88591); gbk = test.changeCharset(iso88591,ChangeCharset.ISO_8859_1, ChangeCharset.GBK); System.out.println("再把ISO-8859-1码的字符串转换成GBK码: " + gbk); System.out.println(); String utf8 = test.toUTF_8(str); System.out.println("转换成UTF-8码: " + utf8); gbk = test.changeCharset(utf8,ChangeCharset.UTF_8, ChangeCharset.GBK); System.out.println("再把UTF-8码的字符串转换成GBK码: " + gbk); System.out.println(); String utf16be = test.toUTF_16BE(str); System.out.println("转换成UTF-16BE码:" + utf16be); gbk = test.changeCharset(utf16be,ChangeCharset.UTF_16BE, ChangeCharset.GBK); System.out.println("再把UTF-16BE码的字符串转换成GBK码: " + gbk); System.out.println(); String utf16le = test.toUTF_16LE(str); System.out.println("转换成UTF-16LE码:" + utf16le); gbk = test.changeCharset(utf16le,ChangeCharset.UTF_16LE, ChangeCharset.GBK); System.out.println("再把UTF-16LE码的字符串转换成GBK码: " + gbk); System.out.println(); String utf16 = test.toUTF_16(str); System.out.println("转换成UTF-16码:" + utf16); gbk = test.changeCharset(utf16,ChangeCharset.UTF_16LE, ChangeCharset.GBK); System.out.println("再把UTF-16码的字符串转换成GBK码: " + gbk); String s = new String("中文".getBytes("UTF-8"),"UTF-8"); System.out.println(s); } }
附件中有源码供参考
- AndroidZIP.rar (1.2 MB)
- 下载次数: 10
更多相关文章
- 一款常用的 Squid 日志分析工具
- 分支和循环(二)(零基础学习C语言)
- GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
- RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
- Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
- Flutter 启动页
- [经验总结]eclipse转向android studio常见问题汇总
- Android(安卓)OTA升级新旧版本任意升级
- android lcm驱动解读及调试