十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
import java.io.File;
创新互联建站是专业的嘉兴网站建设公司,嘉兴接单;提供网站设计制作、做网站,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行嘉兴网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!
public class ZipCompressorByAnt {
private File zipFile;
/**
* 压缩文件构造函数
* @param pathName 最终压缩生成的压缩文件:目录+压缩文件名.zip
*/
public ZipCompressorByAnt(String finalFile) {
zipFile = new File(finalFile);
}
/**
* 执行压缩操作
* @param srcPathName 需要被压缩的文件/文件夹
*/
public void compressExe(String srcPathName) {
System.out.println("srcPathName="+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();
}
}
public class TestZip {
public static void main(String[] args) {
ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\test1.zip ");
zca.compressExe("E:\\test1");
}
}
/*如果 出现ant 的 52 51 50 等版本问题 可以去找对应的ant-1.8.2.jar 我开始用的ant-1.10.1.jar 就是这个包版本高了 一直报verson 52 版本问题*/
件夹又有文件与文件夹(下一个目录里是文件),纯java实现,要实
在JDK中有一个zip工具类:
java.util.zip Provides classes for reading and writing the standard ZIP and
GZIP file formats.
使用此类可以将文件夹或者多个文件进行打包压缩操作。
在使用之前先了解关键方法:
ZipEntry(String name) Creates a new zip entry with the specified name.
使用ZipEntry的构造方法可以创建一个zip压缩文件包的实例,然后通过ZipOutputStream将待压缩的文件以流的形式写进该压缩包中。具体实现代码如下:
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.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 将文件夹下面的文件
* 打包成zip压缩文件
*
* @author admin
*
*/
public final class FileToZip {
private FileToZip(){}
/**
* 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
* @param sourceFilePath :待压缩的文件路径
* @param zipFilePath :压缩后存放路径
* @param fileName :压缩后文件的名称
* @return
*/
public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName){
boolean flag = false;
File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
if(sourceFile.exists() == false){
System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");
}else{
try {
File zipFile = new File(zipFilePath + "/" + fileName +".zip");
if(zipFile.exists()){
System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");
}else{
File[] sourceFiles = sourceFile.listFiles();
if(null == sourceFiles || sourceFiles.length1){
System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
}else{
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024*10];
for(int i=0;isourceFiles.length;i++){
//创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
//读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis, 1024*10);
int read = 0;
while((read=bis.read(bufs, 0, 1024*10)) != -1){
zos.write(bufs,0,read);
}
}
flag = true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//关闭流
try {
if(null != bis) bis.close();
if(null != zos) zos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
return flag;
}
public static void main(String[] args){
String sourceFilePath = "D:\\TestFile";
String zipFilePath = "D:\\tmp";
String fileName = "12700153file";
boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);
if(flag){
System.out.println("文件打包成功!");
}else{
System.out.println("文件打包失败!");
}
}
}
//建立路径这里 不是很明白
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
要保留zip里面的目录结构,所以,是先放入当前目录及上层所有目录
package zip;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.lang3.StringUtils;
public class ZipUtil {
/**
* 递归压缩文件夹
* @param srcRootDir 压缩文件夹根目录的子路径
* @param file 当前递归压缩的文件或目录对象
* @param zos 压缩文件存储对象
* @throws Exception
*/
private static void zip(String srcRootDir, File file, ZipOutputStream zos) throws Exception
{
if (file == null)
{
return;
}
//如果是文件,则直接压缩该文件
if (file.isFile())
{
int count, bufferLen = 1024;
byte data[] = new byte[bufferLen];
//获取文件相对于压缩文件夹根目录的子路径
String subPath = file.getAbsolutePath();
int index = subPath.indexOf(srcRootDir);
if (index != -1)
{
subPath = subPath.substring(srcRootDir.length() + File.separator.length());
}
ZipEntry entry = new ZipEntry(subPath);
zos.putNextEntry(entry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
while ((count = bis.read(data, 0, bufferLen)) != -1)
{
zos.write(data, 0, count);
}
bis.close();
zos.closeEntry();
}
//如果是目录,则压缩整个目录
else
{
//压缩目录中的文件或子目录
File[] childFileList = file.listFiles();
for (int n=0; nchildFileList.length; n++)
{
childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());
zip(srcRootDir, childFileList[n], zos);
}
}
}
/**
* 对文件或文件目录进行压缩
* @param srcPath 要压缩的源文件路径。如果压缩一个文件,则为该文件的全路径;如果压缩一个目录,则为该目录的顶层目录路径
* @param zipPath 压缩文件保存的路径。注意:zipPath不能是srcPath路径下的子文件夹
* @param zipFileName 压缩文件名
* @throws Exception
*/
public static void zip(String srcPath, String zipPath, String zipFileName) throws Exception
{
if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(zipPath) || StringUtils.isEmpty(zipFileName))
{
throw new ParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
CheckedOutputStream cos = null;
ZipOutputStream zos = null;
try
{
File srcFile = new File(srcPath);
//判断压缩文件保存的路径是否为源文件路径的子文件夹,如果是,则抛出异常(防止无限递归压缩的发生)
if (srcFile.isDirectory() zipPath.indexOf(srcPath)!=-1)
{
throw new ParameterException(ICommonResultCode.INVALID_PARAMETER, "zipPath must not be the child directory of srcPath.");
}
//判断压缩文件保存的路径是否存在,如果不存在,则创建目录
File zipDir = new File(zipPath);
if (!zipDir.exists() || !zipDir.isDirectory())
{
zipDir.mkdirs();
}
//创建压缩文件保存的文件对象
String zipFilePath = zipPath + File.separator + zipFileName;
File zipFile = new File(zipFilePath);
if (zipFile.exists())
{
//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
SecurityManager securityManager = new SecurityManager();
securityManager.checkDelete(zipFilePath);
//删除已存在的目标文件
zipFile.delete();
}
cos = new CheckedOutputStream(new FileOutputStream(zipFile), new CRC32());
zos = new ZipOutputStream(cos);
//如果只是压缩一个文件,则需要截取该文件的父目录
String srcRootDir = srcPath;
if (srcFile.isFile())
{
int index = srcPath.lastIndexOf(File.separator);
if (index != -1)
{
srcRootDir = srcPath.substring(0, index);
}
}
//调用递归压缩方法进行目录或文件压缩
zip(srcRootDir, srcFile, zos);
zos.flush();
}
catch (Exception e)
{
throw e;
}
finally
{
try
{
if (zos != null)
{
zos.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/**
* 解压缩zip包
* @param zipFilePath zip文件的全路径
* @param unzipFilePath 解压后的文件保存的路径
* @param includeZipFileName 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含
*/
@SuppressWarnings("unchecked")
public static void unzip(String zipFilePath, String unzipFilePath, boolean includeZipFileName) throws Exception
{
if (StringUtils.isEmpty(zipFilePath) || StringUtils.isEmpty(unzipFilePath))
{
throw new ParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
File zipFile = new File(zipFilePath);
//如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径
if (includeZipFileName)
{
String fileName = zipFile.getName();
if (StringUtils.isNotEmpty(fileName))
{
fileName = fileName.substring(0, fileName.lastIndexOf("."));
}
unzipFilePath = unzipFilePath + File.separator + fileName;
}
//创建解压缩文件保存的路径
File unzipFileDir = new File(unzipFilePath);
if (!unzipFileDir.exists() || !unzipFileDir.isDirectory())
{
unzipFileDir.mkdirs();
}
//开始解压
ZipEntry entry = null;
String entryFilePath = null, entryDirPath = null;
File entryFile = null, entryDir = null;
int index = 0, count = 0, bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
ZipFile zip = new ZipFile(zipFile);
EnumerationZipEntry entries = (EnumerationZipEntry)zip.entries();
//循环对压缩包里的每一个文件进行解压
while(entries.hasMoreElements())
{
entry = entries.nextElement();
//构建压缩包中一个文件解压后保存的文件全路径
entryFilePath = unzipFilePath + File.separator + entry.getName();
//构建解压后保存的文件夹路径
index = entryFilePath.lastIndexOf(File.separator);
if (index != -1)
{
entryDirPath = entryFilePath.substring(0, index);
}
else
{
entryDirPath = "";
}
entryDir = new File(entryDirPath);
//如果文件夹路径不存在,则创建文件夹
if (!entryDir.exists() || !entryDir.isDirectory())
{
entryDir.mkdirs();
}
//创建解压文件
entryFile = new File(entryFilePath);
if (entryFile.exists())
{
//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
SecurityManager securityManager = new SecurityManager();
securityManager.checkDelete(entryFilePath);
//删除已存在的目标文件
entryFile.delete();
}
//写入文件
bos = new BufferedOutputStream(new FileOutputStream(entryFile));
bis = new BufferedInputStream(zip.getInputStream(entry));
while ((count = bis.read(buffer, 0, bufferSize)) != -1)
{
bos.write(buffer, 0, count);
}
bos.flush();
bos.close();
}
}
public static void main(String[] args)
{
String zipPath = "d:\\ziptest\\zipPath";
String dir = "d:\\ziptest\\rawfiles";
String zipFileName = "test.zip";
try
{
zip(dir, zipPath, zipFileName);
}
catch (Exception e)
{
e.printStackTrace();
}
String zipFilePath = "D:\\ziptest\\zipPath\\test.zip";
String unzipFilePath = "D:\\ziptest\\zipPath";
try
{
unzip(zipFilePath, unzipFilePath, true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
有三种方式实现java压缩:
1、jdk自带的包java.util.zip.ZipOutputStream,不足之处,文件(夹)名称带中文时,出现乱码问题,实现代码如下:
/**
* 功能:把 sourceDir 目录下的所有文件进行 zip 格式的压缩,保存为指定 zip 文件
* @param sourceDir 如果是目录,eg:D:\\MyEclipse\\first\\testFile,则压缩目录下所有文件;
* 如果是文件,eg:D:\\MyEclipse\\first\\testFile\\aa.zip,则只压缩本文件
* @param zipFile 最后压缩的文件路径和名称,eg:D:\\MyEclipse\\first\\testFile\\aa.zip
*/
public File doZip(String sourceDir, String zipFilePath) throws IOException {
File file = new File(sourceDir);
File zipFile = new File(zipFilePath);
ZipOutputStream zos = null;
try {
// 创建写出流操作
OutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
zos = new ZipOutputStream(bos);
String basePath = null;
// 获取目录
if(file.isDirectory()) {
basePath = file.getPath();
}else {
basePath = file.getParent();
}
zipFile(file, basePath, zos);
}finally {
if(zos != null) {
zos.closeEntry();
zos.close();
}
}
return zipFile;
}
/**
* @param source 源文件
* @param basePath
* @param zos
*/
private void zipFile(File source, String basePath, ZipOutputStream zos)
throws IOException {
File[] files = null;
if (source.isDirectory()) {
files = source.listFiles();
} else {
files = new File[1];
files[0] = source;
}
InputStream is = null;
String pathName;
byte[] buf = new byte[1024];
int length = 0;
try{
for(File file : files) {
if(file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) + "/";
zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos);
}else {
pathName = file.getPath().substring(basePath.length() + 1);
is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) 0) {
zos.write(buf, 0, length);
}
}
}
}finally {
if(is != null) {
is.close();
}
}
}
2、使用org.apache.tools.zip.ZipOutputStream,代码如下,
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);
}
}
}
3、可以用ant中的org.apache.tools.ant.taskdefs.Zip来实现,更加简单。
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;
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");
}
}