Java MCQ: Which class is used to compress files into ZIP format in Java?
Answer:
Explanation:
The ZipOutputStream
class in Java is used to compress files into the ZIP format. It is part of the java.util.zip
package and provides methods to write compressed data to a ZIP file. The ZipOutputStream
class is commonly used in conjunction with FileOutputStream
to create a new ZIP file and add entries (files) to it.
Here’s an example of how to compress a file into a ZIP format using ZipOutputStream
:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CompressFileToZIP {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("output.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
FileInputStream fis = new FileInputStream("example.txt")) {
ZipEntry zipEntry = new ZipEntry("example.txt");
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) >= 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
System.out.println("File has been compressed into ZIP format.");
} catch (IOException e) {
System.out.println("An error occurred during file compression.");
e.printStackTrace();
}
}
}
In this example, a ZipOutputStream
is created to wrap a FileOutputStream
that writes to output.zip
. The file example.txt
is then read using a FileInputStream
, and its contents are written to the ZIP file as a new entry using the ZipEntry
class.
Compression is a common requirement for reducing file size, particularly when transferring files over a network or storing them efficiently. The ZipOutputStream
class is an essential tool for creating ZIP files in Java.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html