We needed our compress files generated from our apps at work and I went the old way using a fileInputStream and a fileoutputStream:
private static void compressFileToGzipOldWay(File destinationDir, File fileToCompress) throws IOException {
String compressedFilesName = fileToCompress.getName() + ".gz";
File compressedFileDir = new File(destinationDir, compressedFilesName);
FileInputStream fis = new FileInputStream(fileToCompress.getName());
FileOutputStream fos = new FileOutputStream(compressedFileDir);
GZIPOutputStream gzipOS = new GZIPOutputStream(fos);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
gzipOS.write(buffer, 0, len);
}
//close resources
gzipOS.close();
fos.close();
fis.close();
}
In the PR review a coworker let me know that this could be simplified with Files.copy. Strangely enough I haven’t found how to do it online, but I think it’s the superior way.
private File compressFileToGzip(File destinationDir, File fileToCompress) throws IOException {
String compressedFilesName = fileToCompress.getName() + ".gz";
File compressedFileDir = new File(destinationDir, compressedFilesName);
try (GZIPOutputStream gzipOutputStream
= new GZIPOutputStream(Files.newOutputStream(compressedFileDir.toPath()))) {
Files.copy(fileToCompress.toPath(), gzipOutputStream);
}
return compressedFileDir;
}
Recent Comments