Java文件压缩流

code小生 1年前 ⋅ 1656 阅读

一、压缩文件

 

二、解压文件

三、代码实现

package com.jacob;

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.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class Demo {

	// 文件压缩
	public void compress() {
		File source = new File("C:/Users/Admin/Desktop/123.txt");
		File target = new File("C:/Users/Admin/Desktop/测试.zip");
		FileOutputStream f;
		ZipOutputStream z;
		try {
			f = new FileOutputStream(target);
			z = new ZipOutputStream(f);
			if (source.isDirectory()) {
				for (File file : source.listFiles()) {
					zip(z, "", file);
				}
			} else {
				zip(z, "", source);
			}
			z.close();
			f.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void zip(ZipOutputStream a, String string, File file) {
		if (file.isDirectory()) {
			for (File f : file.listFiles()) {
				zip(a, string + file.getName() + File.separator, file);
			}
		} else {
			byte[] b = new byte[1024];
			try {
				FileInputStream fi = new FileInputStream(file);
				int count = -1;
				a.putNextEntry(new ZipEntry(string + file.getName()));
				while ((count = fi.read(b)) != -1) {
					a.write(b, 0, count);
					a.flush();
				}
				fi.close();
				a.closeEntry();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 文件解压
	public void decompress() {
		File f = new File("C:/Users/Admin/Desktop");
		File source = new File("C:/Users/Admin/Desktop/测试.zip");
		FileInputStream fis;
		try {
			fis = new FileInputStream(source);
			ZipInputStream zis = new ZipInputStream(fis);
			byte[] by = new byte[1024];
			ZipEntry ze = null;
			int count = -1;
			FileOutputStream out = null;
			if (!f.exists()) {
				f.mkdirs();
			}

			while (true) {
				ze = zis.getNextEntry();
				out = new FileOutputStream(new File(f, ze.getName()));
				if (ze.isDirectory()) {
					continue;
				}
				if (ze == null) {
					break;
				}
				while ((count = zis.read(by)) != -1) {
					out.write(by, 0, count);
					out.flush();
				}
				out.close();
				zis.closeEntry();
			}
			zis.close();
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Demo demo = new Demo();
		demo.compress();
		// demo.decompress();
	}

}

全部评论: 0

    我有话说: