main
gaoshuguang 10 months ago
parent 7f274fbedf
commit 52580b6613

@ -0,0 +1,85 @@
package com.nmgs.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
/**
* @author: shuguang
* @date: 20250207 11:19
* @description:
*/
public class ZlibCompressor {
/**
* Zlib使
*
* @param inputFile
* @param outputFile
* @throws IOException I/O
*/
public static void compressFile(File inputFile, File outputFile) throws IOException {
try (FileInputStream fis = new FileInputStream(inputFile);
BufferedInputStream bis = new BufferedInputStream(fis); // 使用缓冲区包装输入流
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedOutputStream bos = new BufferedOutputStream(fos); // 使用缓冲区包装输出流
DeflaterOutputStream dos = new DeflaterOutputStream(bos, new Deflater(Deflater.DEFAULT_COMPRESSION, true))) {
byte[] buffer = new byte[1024 * 8]; // 使用更大的缓冲区8KB
int length;
while ((length = bis.read(buffer)) > 0) {
dos.write(buffer, 0, length);
}
}
}
/**
* Zlib
*
* @param data
* @return
*/
public static byte[] compressData(byte[] data) {
Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
deflater.setInput(data);
deflater.finish();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024 * 8]; // 使用更大的缓冲区8KB
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
outputStream.write(buffer, 0, count);
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
deflater.end();
return outputStream.toByteArray();
}
public static void main(String[] args) {
File inputFile = new File("largefile.txt"); // 大文件
File outputFile = new File("largefile.zlib");
long startTime = System.currentTimeMillis();
try {
compressFile(inputFile, outputFile);
System.out.println("文件压缩完成!");
} catch (IOException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("压缩耗时: " + (endTime - startTime) + " 毫秒");
}
}
Loading…
Cancel
Save