作为我的项目自动更新功能的一部分,我的程序从web服务器下载一个zip文件,然后在重新启动应用程序之前将其解压到位(下面是代码逻辑)。zip文件应该在文件更新之后和主应用程序启动之前被删除。
下载和文件更新工作正常,但我面临的问题是,线 Files.delete(file.toPath());
引发类型错误 java.nio.file.FileSystemException
有描述吗 The process cannot access the file because it is being used by another process
. 似乎是 zis.close()
没有有效地释放 update.zip
. 有什么迹象表明我能解决这个问题吗?
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();
}
}
1条答案
按热度按时间hof1towb1#
如果流实现了closable,则应该对其使用“try with resource”。。检查下面https://docs.oracle.com/javase/tutorial/essential/exceptions/tryresourceclose.html