As part of my project auto-update functionality, my program downloads a zip file from a web server and then unzip it in place before relaunching the app (here below is the code logic). The zip file is supposed to be deleted after the files have been updated and before the main app is launched.
The download and files update is working well but the issue I am facing is that the line Files.delete(file.toPath());
throws an error of type java.nio.file.FileSystemException
with the description The process cannot access the file because it is being used by another process
. It seems like the call to zis.close()
is not effectively releasing the handle on update.zip
. Any indication on how I could fix this?
public static void main(String[] args) {
String updateFileName = "update.zip";
boolean updateSuccess=true;
File file = new File(updateFileName);
if (file.exists()) {
String dir = file.getAbsolutePath();
dir = dir.substring(0, dir.length() - 10);
try {
update(updateFileName, dir);
}
catch (Exception e) {
updateSuccess = false;
System.err.print("update failed !");
e.printStackTrace();
}
if (updateSuccess) {
try {
System.err.print("Trying to delete " + file.getAbsolutePath());
Files.delete(Path.of(file.getAbsolutePath()));
} catch (IOException e) {
System.err.print("zip file could not be deleted after update !: " + e );
}
}
}
HO.main(args);
}
private static void update(String zipFile, String _destDir) throws IOException {
int len;
Pattern pattern;
String fileName;
byte[] buffer = new byte[1024];
File destDir = new File(_destDir);
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File destFile = new File(destDir, fileName);
File parentDirectory = destFile.getParentFile();
if (!parentDirectory.exists()) parentDirectory.mkdirs();
else {
if (destFile.exists()) destFile.delete();
}
FileOutputStream fos = new FileOutputStream(destFile, false);
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
}
}