below is the codes, end up the result is a regular file with no .tar.gz extension, can anybody help? thank you.
String reportId = estatConfig.getId().getReportId(); String targetOutPutReportDirForTarAndGzip = homeDir + estatConfig.getLocationOutPdf()+ StatementConstants.OUTPUT_PREFIX_DIR.value()+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("ddMMyyyy")) + EStatementConstants.OUTPUT_POSTFIX_DIR.value() + reportId; String outputPdf = homeDir + File.separatorChar + estatConfig.getLocationOutPdf() + File.separatorChar + reportId + EStatementConstants.EXTENSION_PDF.value(); File outputPdfFile = new File(outputPdf); if (outputPdfFile.exists()) { try { Files.move(Paths.get(outputPdf), Paths.get(targetOutPutReportDirForTarAndGzip), REPLACE_EXISTING);
} catch (IOException e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
logger.info("Exception during moving of pdf file to target gzip dir => " + e.fillInStackTrace());
}
Path targetOutPutReportDirForTarAndGzipPath = Paths.get(targetOutPutReportDirForTarAndGzip);
// get folder name as zip file name
String tarFileName = targetOutPutReportDirForTarAndGzipPath.getFileName().toString()
+ EStatementConstants.TAR_AND_GZIP_EXTENSION.value();
try (OutputStream fOut = Files.newOutputStream(Paths.get(tarFileName));
BufferedOutputStream buffOut = new BufferedOutputStream(fOut);
GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(buffOut);
TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) {
Files.walkFileTree(targetOutPutReportDirForTarAndGzipPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
// only copy files, no symbolic links
if (attributes.isSymbolicLink()) {
return FileVisitResult.CONTINUE;
}
// get filename
Path targetFile = targetOutPutReportDirForTarAndGzipPath.relativize(file);
try {
TarArchiveEntry tarEntry = new TarArchiveEntry(file.toFile(), targetFile.toString());
tOut.putArchiveEntry(tarEntry);
Files.copy(file, tOut);
tOut.closeArchiveEntry();
logger.info("tarred and gzipped: " + file + "successfully");
} catch (IOException e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
logger.info("Unable to tar and gzip: " + file + "=> " + e.fillInStackTrace());
}
return FileVisitResult.CONTINUE;
}
}
}
}
above codes is reference from https://mkyong.com/java/how-to-create-tar-gz-in-java/