栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java Io流之 ZipOutputStream实现文件夹和文件压缩

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java Io流之 ZipOutputStream实现文件夹和文件压缩

 用io流简单实现了一个压缩文件的工具类。

package com.gzh.zip;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipFiles {

	public static void sourceToZip(String sourcePath,String targetPath) throws IOException {

		File sourceFile = new File(sourcePath);

		File targetFile = new File(targetPath);

		if(!sourceFile.exists()) throw new RuntimeException("目标文件不存在");

		if(!targetFile.isDirectory()) throw new RuntimeException("目标路径不是一个文件夹");

		File targetZipFile = null;

		if(!sourceFile.isDirectory()){
			 targetZipFile = new File(targetPath + sourceFile.getName().substring(0, sourceFile.getName().indexOf(".")) + ".zip");
		}else {
			 targetZipFile = new File(targetPath + sourceFile.getName() + ".zip");
		}

		File[] file = sourceFile.listFiles();

		ZipOutputStream zip = null;

		try{

			zip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetZipFile)));

			if(sourceFile.isFile()){
				toZip(sourceFile,zip,"");
			}else {
				fileToZip(sourceFile, zip,"");
			}
		}catch (IOException e){
			e.printStackTrace();
		}finally {
			zip.close();
		}
	}

    //文件压缩
	private static void toZip(File file,ZipOutputStream zip,String targetPath) throws IOException {

		ZipEntry zipEntry = new ZipEntry(targetPath + file.getName());

		byte[] bytes = new byte[1024];

		zip.putNextEntry(zipEntry);

		InputStream read = new FileInputStream(file);

		int ch = -1;

		while((ch = read.read(bytes)) != -1){
			zip.write(bytes, 0, ch);
		}

		read.close();
		zip.closeEntry();
	}
    //文件夹压缩
	private static void fileToZip(File file,ZipOutputStream zip,String targetPath) throws IOException {

		targetPath += file.getName() + File.separator;

		ZipEntry entry = new ZipEntry(targetPath);

		zip.putNextEntry(entry);

		zip.closeEntry();

		if(file.listFiles() == null || file.listFiles().length == 0) return;

		File[] fileLists = file.listFiles();

		for(File file1 : fileLists){
			if(!file1.isDirectory()){
				toZip(file1,zip,targetPath);
			}else {
				fileToZip(file1,zip,targetPath);
			}
		}
	}
}

测试:

public class Test {
	public static void main(String[] args) throws IOException {
		ZipFiles.sourceToZip("C:\Users\DELL\Desktop\css",
                              "C:\Users\DELL\Desktop\");
	}
}

结果:

 

暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1017394.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号