用Java代码实现文件的压缩

从网上找的一些别人写的代码,自己重新写了一下。这是Java自带的不支持中文。密码暂时只支持三个字符的密码。

如果要实现中文格式的文档压缩解压缩就要用

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

来替换。这是ant.jar中的。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class Zip {
	private static final int SIZE = 1024;
	private static final String algorithm = "PBEWithMD5AndDES";
	
	public void compressing(File from, File to) throws Exception {
		compressAndPwd(from, to, null);
	}

	public void compressAndPwd(File from, File to, String pwd) throws Exception {
		ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(to));
		BufferedOutputStream toOut = new BufferedOutputStream(zipOutputStream, SIZE);
		compressing(zipOutputStream, from, from.getName(), toOut, pwd);
		zipOutputStream.close();
		toOut.close();
	}

	public void compressing(ZipOutputStream zipOutputStream, File from, String base, BufferedOutputStream toOut, String pwd) throws Exception {
		if (from.isDirectory()) {
			zipOutputStream.putNextEntry(new ZipEntry(base + "/"));
			File[] files = from.listFiles();
			if (files.length == 0) {
				base = "";
			} else {
				base += "/";
			}
			for (int i = 0; i < files.length; i++) {
				compressing(zipOutputStream, files[i], base + files[i].getName(), toOut, pwd);
			}
			zipOutputStream.closeEntry();
		} else {
			zipOutputStream.putNextEntry(new ZipEntry(base));
			FileInputStream in = new FileInputStream(from);
			BufferedInputStream bis = new BufferedInputStream(in);
			if (pwd == null) {
				System.out.println(base);
				System.out.println(from.length());
				int len = -1;
				while ((len = bis.read()) != -1) {
					toOut.write(len);
				}
				toOut.flush();
			} else {
				ex(zipOutputStream, pwd, in);
			}
			bis.close();
			in.close();
			zipOutputStream.closeEntry();
		}
	}

	public void decompress(File zipFile, File outFile) throws Exception {
		decompress(zipFile, outFile, null);
	}

	public void decompress(File zipFile, File outFile, String pwd) throws Exception {
		// TODO Auto-generated method stub
		long startTime = System.currentTimeMillis();
		if (outFile.exists() && outFile.isDirectory()) {
			outFile.mkdirs();
		}
		ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));// 输入源zip路径
		BufferedInputStream bis = new BufferedInputStream(zis);

		ZipEntry entry = null;//<span style="color:#ff0000;">用ant的时候要用<span style="font-family: Arial, Helvetica, sans-serif;">java.util.zip.</span><span style="font-family: Arial, Helvetica, sans-serif;">ZipEntry</span></span>
		while ((entry = zis.getNextEntry()) != null) {
			if (entry.isDirectory()) {
				String nameString = entry.getName();
				nameString = nameString.substring(0, nameString.length() - 1);
				File file = new File(outFile.getAbsolutePath() + File.separator + nameString);
				if (!file.exists()) {
					file.mkdirs();
				}
			} else {
				System.out.println(outFile.getAbsolutePath() + File.separator + entry.getName());
				File file = new File(outFile.getAbsolutePath() + File.separator + entry.getName());
				file.createNewFile();
				FileOutputStream fos = new FileOutputStream(file);
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				if (pwd == null) {
					int len = -1;
					while ((len = bis.read()) != -1) {
						bos.write(len);
					}
					bos.flush();
				} else {
					decompressAndPwd(zis, fos, pwd);
				}
				bos.close();
				fos.close();
				System.out.println(file.getName() + "解压成功");
			}
		}
		bis.close();
		zis.close();
		long endTime = System.currentTimeMillis();
		System.out.println("耗费时间: " + (endTime - startTime) + " ms");
	}

	public void ex(ZipOutputStream bos, String pwd, FileInputStream bis) throws Exception {
		PBEKeySpec keySpec = new PBEKeySpec(pwd.toCharArray());
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
		SecretKey passwordKey = keyFactory.generateSecret(keySpec);
		byte[] salt = new byte[8];
		Random rnd = new Random();
		rnd.nextBytes(salt);
		int iterations = 100;
		PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.ENCRYPT_MODE, passwordKey, parameterSpec);
		bos.write(salt);
		byte[] input = new byte[64];
		int bytesRead;
		while ((bytesRead = bis.read(input)) != -1) {
			byte[] output = cipher.update(input, 0, bytesRead);
			if (output != null) {
				bos.write(output);
			}
		}
		byte[] output = cipher.doFinal();
		if (output != null) {
			bos.write(output);
		}
		bos.flush();
	}

	public void decompressAndPwd(ZipInputStream bis, FileOutputStream bos, String pwd) throws Exception {
		PBEKeySpec keySpec = new PBEKeySpec(pwd.toCharArray());
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
		SecretKey passwordKey = keyFactory.generateSecret(keySpec);
		byte[] salt = new byte[8];
		bis.read(salt);
		int iterations = 100;
		PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.DECRYPT_MODE, passwordKey, parameterSpec);
		byte[] input = new byte[64];
		int bytesRead;
		while ((bytesRead = bis.read(input)) != -1) {
			byte[] output = cipher.update(input, 0, bytesRead);
			if (output != null) {
				bos.write(output);
			}
		}
		byte[] output = cipher.doFinal();
		if (output != null) {
			bos.write(output);
		}
		bos.flush();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 Java 中的 ZipOutputStream 类来实现分卷压缩成多个文件的功能。以下是一个示例代码,用于将一个大的文件分成多个大小相等的文件进行压缩: ```java import java.io.*; import java.util.zip.*; public class ZipSplitter { public static void splitAndZip(String fileName, int chunkSize) throws IOException { byte[] buffer = new byte[1024]; // Create a ZipOutputStream object for the output file ZipOutputStream out = new ZipOutputStream(new FileOutputStream(fileName + ".zip")); // Read the input file and split it into chunks FileInputStream in = new FileInputStream(fileName); int partCount = 0; while (true) { // Create a new ZipEntry for the chunk ZipEntry entry = new ZipEntry(fileName + ".z" + partCount); out.putNextEntry(entry); // Write the chunk to the output file int count = in.read(buffer); if (count == -1) { break; } out.write(buffer, 0, count); // Close the entry out.closeEntry(); // If the chunk is larger than the specified chunk size, split it into smaller chunks if (out.getBytesWritten() > chunkSize) { out.finish(); out.close(); out = new ZipOutputStream(new FileOutputStream(fileName + ".z" + ++partCount + ".zip")); } } // Close the input and output streams in.close(); out.finish(); out.close(); } public static void main(String[] args) throws IOException { // Split and zip the file "largefile.txt" into chunks of size 1 MB splitAndZip("largefile.txt", 1024 * 1024); } } ``` 这段代码将输入文件 "largefile.txt" 分成大小为 1 MB 的多个文件,并将它们压缩成多个 zip 文件(例如 "largefile.txt.z0.zip"、"largefile.txt.z1.zip"、"largefile.txt.z2.zip" 等)。您可以根据需要调整文件大小和文件名的格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值