How to compress multiple files using gzip in Java?
In Java, the GZIPOutputStream class can be used to compress multiple files. Here is an example code for compressing multiple files:
import java.io.*;
import java.util.zip.GZIPOutputStream;
public class GzipMultipleFiles {
public static void main(String[] args) {
String[] files = {"file1.txt", "file2.txt", "file3.txt"};
try (FileOutputStream fos = new FileOutputStream("compressedFiles.gz");
GZIPOutputStream gzipOS = new GZIPOutputStream(fos)) {
for (String file : files) {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
gzipOS.write(buffer, 0, len);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above example, a string array containing multiple file names is first defined. Then a FileOutputStream and GZIPOutputStream object are created to write data to the compressed file compressedFiles.gz. Next, each file is looped through, the file contents are read using FileInputStream, and the contents are written to the GZIPOutputStream, allowing for compression of multiple files. Finally, any possible IOException is caught in the exception handling.