I am trying unzip a file but when I am executing it for the first time it is getting failed although the file is getting downloaded and is in directory. Executing it for the second time it is working fine.
public class UnzipLatestZipFile {
private String unzippedFileName;
public void processLatestZipFile() {
String downloadsFolderPath = System.getProperty("user.home") + File.separator + "Downloads";
String unzippedFolderPath = downloadsFolderPath + File.separator + "unzipped";
File latestZipFile = getLatestZipFile(downloadsFolderPath);
if (latestZipFile != null) {
System.out.println("Latest Zip File: " + latestZipFile.getName());
try {
unzipFile(latestZipFile, unzippedFolderPath);
System.out.println("File successfully unzipped to: " + unzippedFolderPath);
System.out.println("Unzipped File Name: " + unzippedFileName);
} catch (IOException e) {
System.err.println("Error unzipping file: " + e.getMessage());
}
} else {
System.out.println("No zip files found in the Downloads folder.");
}
}
private File getLatestZipFile(String folderPath) {
File downloadsFolder = new File(folderPath);
File[] files = downloadsFolder.listFiles((dir, name) -> name.toLowerCase().endsWith(".zip"));
if (files != null && files.length > 0) {
Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
return files[0];
}
return null;
}
private void unzipFile(File zipFile, String outputFolder) throws IOException {
byte[] buffer = new byte[1024];
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile))) {
File outputDir = new File(outputFolder);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
String entryName = zipEntry.getName();
File entryFile = new File(outputFolder + File.separator + entryName);
new File(entryFile.getParent()).mkdirs();
if (!zipEntry.isDirectory()) {
try (FileOutputStream fos = new FileOutputStream(entryFile)) {
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
unzippedFileName = entryFile.getName();
}
zipEntry = zipInputStream.getNextEntry();
}
}
}
}
I am expecting it to get executed every time, not that I have to rerun it.