文件压缩、解压是开发中常见的一些操作,在这里做一个记录:
1.文件解压:
public static void UnZipFolder(String zipFileString, String outPathString)throws Exception {
Log.i("lingeng", "开始unzip: ");
File f = new File(outPathString);
if (!f.isDirectory()) {
Log.i("lingeng", "创建文件夹: ");
f.mkdirs();
}
ZipInputStream inZip = new ZipInputStream(new java.io.FileInputStream(zipFileString));
ZipEntry zipEntry;
String szName = "";
while ((zipEntry = inZip.getNextEntry()) != null) {
szName = zipEntry.getName();
if (zipEntry.isDirectory()) {
// get the folder name of the widget
szName = szName.substring(0, szName.length() - 1);
File folder = new File(outPathString + java.io.File.separator + szName);
folder.mkdirs();
} else {
java.io.File file = new java.io.File(outPathString + java.io.File.separator + szName);
file.createNewFile();
// get the output stream of the file
java.io.FileOutputStream out = new java.io.FileOutputStream(file);
int len;
byte[] buffer = new byte[1024];
// read (len) bytes into buffer
while ((len = inZip.read(buffer)) != -1) {
// write (len) byte from buffer at the position 0
out.write(buffer, 0, len);
out.flush();
}
out.close();
}
}
inZip.close();
}
2.文件压缩:
static final int BUFFER_SIZE = 1024;
//多个文件压缩成一个zip
public static void zip(List<FN> files, String zipFile) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
try {
byte data[] = new byte[BUFFER_SIZE];
for (int i = 0; i < files.size(); i++) {
FileInputStream fi = new FileInputStream(files.get(i).path);
origin = new BufferedInputStream(fi, BUFFER_SIZE);
try {
ZipEntry entry = new ZipEntry(files.get(i).filename);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
} finally {
origin.close();
}
}
} finally {
out.close();
}
}
//将文件压缩成一个zip
public static void zip(String filepath, String name) throws IOException {
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(filepath));
ZipEntry ze = new ZipEntry(name);
zout.putNextEntry(ze);
zout.finish();
}