使用 Deflater/Inflater 壓縮和解壓縮位元組數組
瀏覽人數:706最近更新:
1. 概述
資料壓縮是軟體開發的重要方面,可以實現資訊的高效儲存和傳輸。在 Java 中, java.util.zip
套件中的[Deflater](https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html)
和Inflater
類別提供了一種壓縮和解壓縮位元組數組的直接方法。
在這個簡短的教程中,我們將透過一個簡單的範例探索如何使用這些類別。
2. 壓縮
Deflater
類別使用 ZLIB 壓縮函式庫來壓縮資料。讓我們看看它的實際效果:
public static byte[] compress(byte[] input) {
Deflater deflater = new Deflater();
deflater.setInput(input);
deflater.finish();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int compressedSize = deflater.deflate(buffer);
outputStream.write(buffer, 0, compressedSize);
}
return outputStream.toByteArray();
}
在上面的程式碼中,我們使用了Deflater
類別的幾個方法來壓縮輸入資料:
-
setInput()
:設定用於壓縮的輸入數據 -
finish()
:指示壓縮應以輸入的目前內容結束 -
deflate()
:壓縮資料並填入指定緩衝區,然後傳回壓縮資料的實際位元組數 -
finished()
:檢查壓縮資料輸出流是否已到達末尾
此外,我們可以使用setLevel()
方法來獲得更好的壓縮結果。我們可以傳遞從 0 到 9 的值,對應於從無壓縮到最佳壓縮的範圍:
Deflater deflater = new Deflater();
deflater.setInput(input);
deflater.setLevel(5);
3.解壓
接下來,讓我們使用Inflater
類別解壓縮位元組數組:
public static byte[] decompress(byte[] input) throws DataFormatException {
Inflater inflater = new Inflater();
inflater.setInput(input);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
int decompressedSize = inflater.inflate(buffer);
outputStream.write(buffer, 0, decompressedSize);
}
return outputStream.toByteArray();
}
這次,我們使用了Inflater
類別的三個方法:
-
setInput()
:設定解壓縮輸入數據 -
finished()
:檢查壓縮資料流是否已到達末尾 -
inflate()
:將位元組解壓縮到指定緩衝區並傳回未壓縮的實際位元組數
4. 範例
讓我們用這個簡單的例子來嘗試我們的方法:
String inputString = "Baeldung helps developers explore the Java ecosystem and simply be better engineers. "
+ "We publish to-the-point guides and courses, with a strong focus on building web applications, Spring, "
+ "Spring Security, and RESTful APIs";
byte[] input = inputString.getBytes();
byte[] compressedData = compress(input);
byte[] decompressedData = decompress(compressedData);
System.out.println("Original: " + input.length + " bytes");
System.out.println("Compressed: " + compressedData.length + " bytes");
System.out.println("Decompressed: " + decompressedData.length + " bytes");
assertEquals(input.length, decompressedData.length);
結果將如下所示:
Original: 220 bytes
Compressed: 168 bytes
Decompressed: 220 bytes
5. 結論
在本文中,我們學習如何分別使用Deflater
和Inflater
類別來壓縮和解壓縮 Java 位元組數組。
本文中的範例程式碼可以在 GitHub 上找到。
本作品係原創或者翻譯,採用《署名-非商業性使用-禁止演繹4.0國際》許可協議