Java 文件压缩和解压 Zip and Unzip

写了些代码,也没有完全总结好,把代码沾上了,以便让后人鉴。

package net.northking.bpoweb.project.service.impl.process.longjiangcard.tools.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import com.northking.util.tiger.TigerException;


public class FileToZipTool {
public static int fileNum = 0;
   
    public void fileToZip(String zipFileName, String filePath) {
        ZipOutputStream zipOut = null;

        try {
        // 删除上一次的生成zip包
        this.deleteFile(zipFileName);
            zipOut = new ZipOutputStream(new FileOutputStream(zipFileName));
            forEachFileToZip(zipOut, new File(filePath), "");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new TigerException("zip文件没有找到");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new TigerException("文件打zip异常");
        } finally {
            if (zipOut != null) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    throw new TigerException("ZipOutputStream关闭出错");
                }
            }
        }
    }

   
    private void forEachFileToZip(ZipOutputStream zipOut, File sourceFile,
        String baseFile) throws Exception {
        if (sourceFile.isDirectory()) {
            File[] subFile = sourceFile.listFiles();
            zipOut.putNextEntry(new ZipEntry(baseFile + "/"));
            baseFile = (baseFile.length() == 0) ? "" : (baseFile + "/");

            for (int i = 0; i < subFile.length; i++) {
                forEachFileToZip(zipOut, subFile[i], baseFile + subFile[i].getName());
            }
        } else {
            zipOut.putNextEntry(new ZipEntry(baseFile));

            BufferedInputStream bufferInputStream = new BufferedInputStream(new FileInputStream(
                        sourceFile));

            int lineData;

            while ((lineData = bufferInputStream.read()) != -1) {
                zipOut.write(lineData);
            }

            bufferInputStream.close();
        }
    }

   
    public void downZip(String zipFileName) {
        BufferedInputStream bis = null;
        OutputStream os = null;
        File file = new File(zipFileName);

        if (file.exists()) {
            try {
                bis = new BufferedInputStream(new FileInputStream(file));

                byte[] buffer = new byte[1024];

                os = new ByteArrayOutputStream();

                while (bis.read(buffer) > 0) {
                    os.write(buffer);
                }

                os.flush();
            } catch (Exception e) {
                throw new TigerException(e);
            } finally {
                try {
                    if (bis != null) {
                        bis.close();
                    }

                    if (os != null) {
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new TigerException(e);
                }
            }
        } else {
            throw new TigerException("没有此文件");
        }
    }
    
   
    public void deleteFile(String zipFileName){
    File zipFile = new File(zipFileName);
    if(!zipFile.isDirectory() && zipFile.exists()){
    zipFile.delete();
    }
    }

    
   
public int fileCopy(File sourceFile, File destFile) {
if (!sourceFile.exists()) {
throw new TigerException("源文件:" + sourceFile.getAbsolutePath() + "不存在");
}

// 如果文件已存在,且不是文件夹,则异常
if (destFile.exists() && !destFile.isDirectory()) {
throw new TigerException("目标路径已存在,且不是文件夹");
}

// 如果文件不存在,则新建
if (destFile.exists()) {
destFile.delete();
}

destFile.mkdirs();

// 开始进行文件拷贝
try {
if (!sourceFile.isDirectory()) {
// copy
fileChannelCopy(sourceFile, new File(destFile
.getAbsolutePath()
+ File.separator + sourceFile.getName()));
fileNum ++;
} else if (sourceFile.isDirectory()) {
String[] filelist = sourceFile.list();

for (int i = 0; i < filelist.length; i++) {
File delfile = new File(sourceFile.getAbsolutePath()
+ File.separator + filelist[i]);

if (!delfile.isDirectory()) {
// copy
fileChannelCopy(delfile, new File(destFile
.getAbsolutePath()
+ File.separator + filelist[i]));
fileNum++;
} else {
// 迭代调用
fileCopy(delfile, new File(destFile.getAbsolutePath()
+ File.separator + filelist[i]));
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("deletefile() Exception:" + e.getMessage());
}
return fileNum;
}
public void fileCopy(String[] sourceFilePath, String[] destFilePath) {
// sourceFilePath,destFilePath肯定为一一对应的字条串
for(int i=0; i
// 判断源文件是否存在
File sourceFile = new File(sourceFilePath[i]);
if (!sourceFile.exists()) {
throw new TigerException("文件:"+ sourceFilePath[i] + " 不存在");
}
// 判断目标文件的文件路径是否已存在
File destFile = new File(destFilePath[i]);
if(!destFile.getParentFile().exists()){
destFile.getParentFile().mkdir();
}
// 判断目标文件是否已存在,如果存在,则删除
if (destFile.exists()) {
destFile.delete();
}
fileChannelCopy(sourceFile, destFile);
}
}

public void fileChannelCopy(File sourceFile, File destFile) {
FileChannel fileInChannel = null;
FileChannel fileOutChannel = null;
try {
fileInChannel = new FileInputStream(sourceFile)
.getChannel();
fileOutChannel = new FileOutputStream(destFile)
.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(8092);

// 下面语句也可实现
// fileInChannel.transferTo(0,fileInChannel.size(),fileOutChannel);
while (fileInChannel.read(byteBuffer) != -1) {
byteBuffer.flip();
fileOutChannel.write(byteBuffer);
byteBuffer.clear(); // prepare for reading;清空缓冲区;
}
} catch (Exception e) {
throw new TigerException("文件拷贝出错");
} finally {
if(fileInChannel!=null){
try {
fileInChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fileOutChannel!=null){
try {
fileOutChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void fileDelete(File sourceFile) {
if (!sourceFile.isDirectory()) {
sourceFile.delete();
} else {
String[] filelist = sourceFile.list();

for (int i = 0; i < filelist.length; i++) {
File delfile = new File(sourceFile.getAbsolutePath()
+ File.separator + filelist[i]);

if (!delfile.isDirectory()) {
delfile.delete();

if (delfile.getParentFile().length() == 0) {
delfile.getParentFile().delete();
}
} else {
// 迭代调用
fileDelete(new File(sourceFile.getAbsolutePath()
+ File.separator + filelist[i]));
}
}
}
}
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;
BufferedOutputStream bops = 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.length < 1) {
System.out.println(">>>>>> 待压缩的文件目录:" + sourceFilePath + " 里面不存在文件,无需压缩. <<<<<<");
} else {
fos = new FileOutputStream(zipFile);
bops = new BufferedOutputStream(fos);
zos = new ZipOutputStream(bops);
byte[] bufs = new byte[1024*10];
for(int i=0;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);
}
fis.close();
}
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();
if(fis!=null) fis.close();
if(fos!=null) fos.close();
if(bops!=null) bops.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
return flag;
}
public Boolean unzip(String fileName, String unzipFilePath){
Boolean result = false;
int buffer = 2048;
try {
           ZipFile zipFile = new ZipFile(fileName);
           Enumeration emu = zipFile.entries();
           int i=0;
           while(emu.hasMoreElements()){
               ZipEntry entry = (ZipEntry)emu.nextElement();
               //会把目录作为一个file读出一次,所以只建立目录就可以,之下的文件还会被迭代到。
               if (entry.isDirectory())
               {
                   new File(unzipFilePath + entry.getName()).mkdirs();
                   continue;
               }
               BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
               File file = new File(unzipFilePath + entry.getName());
               //加入这个的原因是zipfile读取文件是随机读取的,这就造成可能先读取一个文件
               //而这个文件所在的目录还没有出现过,所以要建出目录来。
               File parent = file.getParentFile();
               if(parent != null && (!parent.exists())){
                   parent.mkdirs();
               }
               FileOutputStream fos = new FileOutputStream(file);
               BufferedOutputStream bos = new BufferedOutputStream(fos,buffer);           
               
               int count;
               byte data[] = new byte[buffer];
               while ((count = bis.read(data, 0, buffer)) != -1)
               {
                   bos.write(data, 0, count);
               }
               bos.flush();
               bos.close();
               bis.close();
           }
           zipFile.close();
           result = true;
       } catch (Exception e) {
           e.printStackTrace();
           result = false;
       }
return result;
}
    public static void main(String[] args) {
        // TODO Auto-generated method stub
   
        
    FileToZipTool fileToZipTool = new FileToZipTool();
    fileToZipTool.unzip("D:\\test\\201209280013.zip","D:\\test\\201209280013\\");
    }
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值