Java Gzip Compression: File Naming Guide
In Java, you can use the GZIPOutputStream class to compress a file and specify the name for the compressed file. Below is an example code demonstrating how to achieve this using the GZIPOutputStream class.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GzipFileCompression {
public static void main(String[] args) {
String inputFileName = "input.txt";
String outputFileName = "output.gz";
try (FileInputStream fis = new FileInputStream(inputFileName);
FileOutputStream fos = new FileOutputStream(outputFileName);
GZIPOutputStream gzipOS = new GZIPOutputStream(fos)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
gzipOS.write(buffer, 0, bytesRead);
}
System.out.println("File compressed successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, input.txt is the name of the file to be compressed, and output.gz is the name of the compressed file. Data is written to the specified output file by creating a FileOutputStream object, and compression is achieved by creating a GZIPOutputStream object.
Remember to replace the file names of input.txt and output.gz with the actual file names you want to operate on.