java压缩和解压缩例子
压缩时,在压缩文件夹中新建目录,entry名称必须以“/”结尾。
压缩后,如果用rar工具解压,发现中文名称的文件都是乱码,但是如果用java程序解压就不会有事,网上有很多关于这个问题及解决方案
Java代码
/**按照POS目录要求压缩文件
* @param out
* @param f
* @param base
* @param serverTime 14位的时间戳
* @param buzName 业务名称
* @throws Exception
*/
public static void zip4Pos(String zipFileName, String inputPath, String base, String buzName, String serverTime)
{
File f = new File(inputPath);
ZipOutputStream out;
logger.info("正在压缩:" + f.getName() + "... ...");
try
{
out = new ZipOutputStream(new FileOutputStream(zipFileName));
String buzp = buzName + "/";
String yp = buzp + serverTime.substring(0,4)+"/";
String mp = yp + serverTime.substring(4,6)+"/";
out.putNextEntry(new ZipEntry(buzp));
out.putNextEntry(new ZipEntry(yp));
out.putNextEntry(new ZipEntry(mp));
base = mp + f.getName();
zip(out, f, base);
out.close();
}
catch (Exception e)
{
logger.error(e);
e.printStackTrace();
}
}
private static void zip(ZipOutputStream out, File f, String base)
throws Exception
{
logger.info("正在压缩:" + f.getName() + "... ...");
if (f.isDirectory())
{
File[] fs = f.listFiles();
base += "/";
logger.info("新建目录条目:" + f.getName());
out.putNextEntry(new ZipEntry(base)); // 生成相应的目录
for (int i = 0; i < fs.length; i++)
{
// 对本目录下的所有文件对象递归调用本方法
zip(out, fs[i], base + fs[i].getName());
}
}
else
{
logger.info("新增文件条目:" + f.getName());
out.putNextEntry(new ZipEntry(base));
InputStream is = new FileInputStream(f);
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1)
{
out.write(buf, 0, len);
}
is.close();
}
}
/**
* 解压缩文件
* @param zipFile
* @param desPath
*/
public static void unZip(File zipFile, String desPath)
{
// 建立输出流,用于将从压缩文件中读出的文件流写入到磁盘
OutputStream out = null;
// 建立输入流,用于从压缩文件中读出文件
ZipInputStream is;
try
{
is = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry entry = null;
while ((entry = is.getNextEntry()) != null)
{
logger.info("正在解压缩:" + entry.getName() + "... ...");
File f = new File(desPath + "\\" + entry.getName());
if (entry.isDirectory())
{
logger.info("新建目录:" + f.getName());
f.mkdir();
}
else
{
logger.info("新增文件:" + f.getName());
// 根据压缩文件中读出的文件名称新建文件
out = new FileOutputStream(f);
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1)
{
out.write(buf, 0, len);
}
out.close();
}
}
is.close();
}
catch (Exception e)
{
logger.error(e);
}
}
由于java.util.zip.ZipOutputStream有中文乱码问题,所以采用org.apache.tools.zip.ZipOutputStream。
以下是代码:
Java代码
package net.szh.zip;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class ZipCompressor {
static final int BUFFER = 8192;
private File zipFile;
public ZipCompressor(String pathName) {
zipFile = new File(pathName);
}
public void compress(String srcPathName) {
File file = new File(srcPathName);
if (!file.exists())
throw new RuntimeException(srcPathName + "不存在!");
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
String basedir = "";
compress(file, out, basedir);
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void compress(File file, ZipOutputStream out, String basedir) {
/* 判断是目录还是文件 */
if (file.isDirectory()) {
System.out.println("压缩:" + basedir + file.getName());
this.compressDirectory(file, out, basedir);
} else {
System.out.println("压缩:" + basedir + file.getName());
this.compressFile(file, out, basedir);
}
}
/** 压缩一个目录 */
private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())
return;
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/* 递归 */
compress(files[i], out, basedir + dir.getName() + "/");
}
}
/** 压缩一个文件 */
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream 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);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package net.szh.zip;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class ZipCompressor {
static final int BUFFER = 8192;
private File zipFile;
public ZipCompressor(String pathName) {
zipFile = new File(pathName);
}
public void compress(String srcPathName) {
File file = new File(srcPathName);
if (!file.exists())
throw new RuntimeException(srcPathName + "不存在!");
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
String basedir = "";
compress(file, out, basedir);
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void compress(File file, ZipOutputStream out, String basedir) {
/* 判断是目录还是文件 */
if (file.isDirectory()) {
System.out.println("压缩:" + basedir + file.getName());
this.compressDirectory(file, out, basedir);
} else {
System.out.println("压缩:" + basedir + file.getName());
this.compressFile(file, out, basedir);
}
}
/** 压缩一个目录 */
private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())
return;
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/* 递归 */
compress(files[i], out, basedir + dir.getName() + "/");
}
}
/** 压缩一个文件 */
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream 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);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
后来发现原来可以用ant中的org.apache.tools.ant.taskdefs.Zip来实现,更加简单。
Java代码
package net.szh.zip;
import java.io.File;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
public class ZipCompressorByAnt {
private File zipFile;
public ZipCompressorByAnt(String pathName) {
zipFile = new File(pathName);
}
public void compress(String srcPathName) {
File srcdir = new File(srcPathName);
if (!srcdir.exists())
throw new RuntimeException(srcPathName + "不存在!");
Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(srcdir);
//fileSet.setIncludes("**/*.java"); 包括哪些文件或文件夹 eg:zip.setIncludes("*.java");
//fileSet.setExcludes(...); 排除哪些文件或文件夹
zip.addFileset(fileSet);
zip.execute();
}
}
package net.szh.zip;
import java.io.File;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
public class ZipCompressorByAnt {
private File zipFile;
public ZipCompressorByAnt(String pathName) {
zipFile = new File(pathName);
}
public void compress(String srcPathName) {
File srcdir = new File(srcPathName);
if (!srcdir.exists())
throw new RuntimeException(srcPathName + "不存在!");
Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(srcdir);
//fileSet.setIncludes("**/*.java"); 包括哪些文件或文件夹 eg:zip.setIncludes("*.java");
//fileSet.setExcludes(...); 排除哪些文件或文件夹
zip.addFileset(fileSet);
zip.execute();
}
}
测试一下
Java代码
package net.szh.zip;
public class TestZip {
public static void main(String[] args) {
ZipCompressor zc = new ZipCompressor("E:\\szhzip.zip");
zc.compress("E:\\test");
ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\szhzipant.zip");
zca.compress("E:\\test");
}
}