Welkom bij het Java GZIP-voorbeeld. GZIP is een van de favoriete tools om bestanden te comprimeren in Unix-systemen. We kunnen een enkel bestand in GZIP-indeling comprimeren, maar we kunnen geen directory comprimeren en archiveren met GZIP zoals bij ZIP-bestanden.
Java GZIP
Hier is een eenvoudig Java GZIP-voorbeeldprogramma dat laat zien hoe we een bestand naar GZIP-indeling kunnen comprimeren en vervolgens het GZIP-bestand kunnen decomprimeren om een nieuw bestand te maken.
GZIPExample.java
package com.journaldev.files;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPExample {
public static void main(String[] args) {
String file = "/Users/pankaj/sitemap.xml";
String gzipFile = "/Users/pankaj/sitemap.xml.gz";
String newFile = "/Users/pankaj/new_sitemap.xml";
compressGzipFile(file, gzipFile);
decompressGzipFile(gzipFile, newFile);
}
private static void decompressGzipFile(String gzipFile, String newFile) {
try {
FileInputStream fis = new FileInputStream(gzipFile);
GZIPInputStream gis = new GZIPInputStream(fis);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int len;
while((len = gis.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
// sluit resources
fos.close();
gis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void compressGzipFile(String file, String gzipFile) {
try {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(gzipFile);
GZIPOutputStream gzipOS = new GZIPOutputStream(fos);
byte[] buffer = new byte[1024];
int len;
while((len=fis.read(buffer)) != -1){
gzipOS.write(buffer, 0, len);
}
// sluit resources
gzipOS.close();
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Tijdens het decomprimeren van een GZIP-bestand, als het niet in GZIP-indeling is, wordt de volgende uitzondering gegenereerd.
java.util.zip.ZipException: Not in GZIP format
at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:164)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:78)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:90)
at com.journaldev.files.GZIPExample.decompressGzipFile(GZIPExample.java:25)
at com.journaldev.files.GZIPExample.main(GZIPExample.java:18)
Dat is alles voor het Java GZIP-voorbeeld.
Source:
https://www.digitalocean.com/community/tutorials/java-gzip-example-compress-decompress-file