JAVA实现文件的压缩与解压

压缩

public class ZipUtilt {
	public static boolean toZip(ServletResponse response, String filePath) {
		try {
			// 获取被压缩文件
			File file = new File(filePath);
			// 从压缩文件中获取输出流
			OutputStream baseOS = response.getOutputStream();
			ZipOutputStream zipOutputStream = new ZipOutputStream(baseOS);
			// 被压缩文件和目录分不同的方式压缩
			boolean isSuccess=fileToZip(file, zipOutputStream, "");
			zipOutputStream.flush();
			zipOutputStream.close();
			baseOS.flush();
			baseOS.close();
			return isSuccess;
			
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}

	// 主要是针对目录好做递归处理抽取方法
	public static boolean fileToZip(File file, ZipOutputStream zipOutputStream, String zipEntryName) throws Exception {
		if (file.isFile()) {
			// 获取zip实体的名字(zip文件内的文件路径,单个“/”表示压缩包内的顶级目录)
			if(zipEntryName.isEmpty()) {
				zipEntryName = file.getName().replaceAll("\\\\", "/");
			}else {
				zipEntryName = zipEntryName + "/" + file.getName().replaceAll("\\\\", "/");
			}
			// 从被压缩件中获取输入流,读取被压缩文件
			InputStream baseIS = new FileInputStream(file);
			// 向输出流中放入一个zipEntry:zipEntryName就是压缩文件内容的路径,一个zipEntry就是压缩文件中的一个条目
			ZipEntry zipEntry=new ZipEntry(zipEntryName);
			zipOutputStream.putNextEntry(zipEntry);
			byte[] bytes = new byte[1024];
			int lengeth;
			while ((lengeth = baseIS.read(bytes)) != -1) {
				zipOutputStream.write(bytes, 0, lengeth);
				
			}
			// 关闭资源
			baseIS.close();
			zipOutputStream.flush();
			zipOutputStream.closeEntry();
			return true;
		} else {
			// 如果是目录
			if(zipEntryName.isEmpty()) {
				zipEntryName = file.toString().substring(file.toString().replaceAll("\\\\", "/").lastIndexOf("/") + 1);
			}else {
				zipEntryName = zipEntryName + "/"+ file.toString().substring(file.toString().replaceAll("\\\\", "/").lastIndexOf("/") + 1);
			}
			File[] files = file.listFiles();
			// 如果目录中没有文件(空目录)
			if (files == null || files.length == 0) {
				// 需要保留原来的文件结构时,需要对空文件夹进行处理
				if (true) {
					// 如果是空文件夹就按照原来的路径存放
					zipOutputStream.putNextEntry(new ZipEntry(zipEntryName + "/"));
					// 没有文件关闭资源
					zipOutputStream.closeEntry();
				}
			} else {
				zipOutputStream.putNextEntry(new ZipEntry(zipEntryName + "/"));
				for (File contentFile : files) {
					fileToZip(contentFile, zipOutputStream, zipEntryName);
				}
			}
			return true;
		}

	}
}

解压

//解压文件
public class ZipUtilt {
	public static void zipToFile(String zipPath){
		try {
			InputStream fileImputStream = new FileInputStream(zipPath);
			String encoding = System.getProperty("file.encoding");
			ZipInputStream zipInputStream = new ZipInputStream(fileImputStream, Charset.forName(encoding));
			ZipEntry zipentry = null;
			while ((zipentry =zipInputStream.getNextEntry())!=null){
				String filePath = zipPath.substring(0,zipPath.indexOf("."))+"/"+zipentry.getName();
				File file = FileUtils.getFile(filePath);
				if (zipentry.isDirectory()){
					if (!file.exists()){
						file.mkdirs();
					}else {
						return;
					}
				}else {
					if (!file.exists()){
						File parentFile = file.getParentFile();
						if (!parentFile.exists()) {
							parentFile.mkdirs();
						}
						FileOutputStream fileOutputStream = new FileOutputStream(filePath);
						byte[] bytes = new byte[1024];
						int length = -1;
						while ((length=zipInputStream.read(bytes))!=-1){
							fileOutputStream.write(bytes,0,length);
						}
					}else {
						return;
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {
		zipToFile("E:/Project/java是世界上最好的语言.zip");
	}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java提供了ZipOutputStream类和ZipInputStream类,用于压缩解压缩文件压缩文件: ```java import java.io.*; import java.util.zip.*; public class ZipFile { public static void main(String[] args) throws Exception { // 创建压缩文件输出流 FileOutputStream fos = new FileOutputStream("test.zip"); ZipOutputStream zos = new ZipOutputStream(fos); // 创建要压缩文件输入流 FileInputStream fis = new FileInputStream("test.txt"); BufferedInputStream bis = new BufferedInputStream(fis); // 开始压缩文件 zos.putNextEntry(new ZipEntry("test.txt")); int len; byte[] buffer = new byte[1024]; while ((len = bis.read(buffer)) > 0) { zos.write(buffer, 0, len); } // 关闭流 bis.close(); zos.closeEntry(); zos.close(); fos.close(); } } ``` 解压文件: ```java import java.io.*; import java.util.zip.*; public class UnzipFile { public static void main(String[] args) throws Exception { // 创建压缩文件输入流 FileInputStream fis = new FileInputStream("test.zip"); ZipInputStream zis = new ZipInputStream(fis); // 开始解压缩文件 ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); File file = new File(fileName); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); int len; byte[] buffer = new byte[1024]; while ((len = zis.read(buffer)) > 0) { bos.write(buffer, 0, len); } // 关闭流 bos.close(); fos.close(); zipEntry = zis.getNextEntry(); } // 关闭流 zis.closeEntry(); zis.close(); fis.close(); } } ``` 以上是基本的压缩解压缩文件实现方法,也可以使用更高级的类库,如Apache Commons Compress。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值