一个简单压缩解压工具类
public class ziputils {
public static void compressfolder(activity activity, string sourcepath, string zipfile) throws ioexception {
file folder = new file(sourcepath);
file zippath = new file(zipfile);
if (zippath.exists()) {
zippath.delete();
}
// 创建输出流并指定要生成的zip文件路径
try (zipoutputstream zos = new zipoutputstream(new fileoutputstream(zipfile))) {
addfilestozip(folder, folder.getname(), zos);
system.out.println("文件夹已成功压缩为 " + zipfile);
toast.maketext(activity, "压缩已完成", toast.length_short).show();
} catch (ioexception e) {
throw new runtimeexception("无法将文件夹压缩到zip文件中", e);
}
}
private static void addfilestozip(file file, string parentname, zipoutputstream zos) throws ioexception {
if (!file.exists()) return;
for (file child : file.listfiles()) {
if (child.isdirectory()) {
addfilestozip(child, parentname + "/" + child.getname(), zos);
} else {
byte[] buffer = new byte[1024];
// 获取当前文件相对于源文件夹的路径名称
string entryname = parentname + "/" + child.getname();
// 添加新条目到zip文件中
zos.putnextentry(new zipentry(entryname));
// 读取文件内容并写入zip文件
try (inputstream is = new fileinputstream(child)) {
int length;
while ((length = is.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
} finally {
zos.closeentry();
}
}
}
}
public static void unzip(string zipfile, string targetdir) {
log.e("lz>>","zipfile:"+zipfile+" targetdir:"+targetdir);
int buffer = 4096; //这里缓冲区我们使用4kb,
string strentry; //保存每个zip的条目名称
try {
bufferedoutputstream dest = null; //缓冲输出流
fileinputstream fis = new fileinputstream(zipfile);
zipinputstream zis = new zipinputstream(new bufferedinputstream(fis));
zipentry entry; //每个zip条目的实例
while ((entry = zis.getnextentry()) != null) {
try {
log.i("unzip: ","="+ entry);
int count;
byte data[] = new byte[buffer];
strentry = entry.getname();
file entryfile = new file(targetdir + strentry);
file entrydir = new file(entryfile.getparent());
if (!entrydir.exists()) {
entrydir.mkdirs();
}
fileoutputstream fos = new fileoutputstream(entryfile);
dest = new bufferedoutputstream(fos, buffer);
while ((count = zis.read(data, 0, buffer)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} catch (exception ex) {
ex.printstacktrace();
}
}
zis.close();
log.i("unzip: ","="+ "结束");
} catch (exception cwj) {
cwj.printstacktrace();
}
}压缩使用:
file appdir = getfilesdir();
string filepath = appdir+“”";//需要压缩的文件路径
string zipwalletfile = zipfile.getabsolutepath();
try {
//zipwalletfile + "/wallet.zip"压缩后的文件名
ziputils.compressfolder(zipactivity.this, filepath , zipwalletfile + "/wallet.zip");
} catch (exception e) {
throw new runtimeexception(e);
}解压使用:
file zipfile = environment.getexternalstoragedirectory();
string zipwalletfile = zipfile.getabsolutepath();//待解压文件
string unzippath=getfilesdir().getpath();解压文件路径
ziputils.unzip(zipwalletfile + "/wallet.zip",unzippath+"/");到此这篇关于android实现文件压缩与解压工具类的文章就介绍到这了,更多相关android文件压缩解压内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论