Не удаляется файл java после распаковки
Уже задавал вопрос на эту тему, но, видимо, дал недостаточно информации/некорректно задал.
У меня есть функция, в которую подаются 2 параметра: путь к архиву и директория его распаковки. После распаковки архива сам архив должен удаляться, но, не смотря на то, что он должен, он не удаляется.
Пробовал "ловить" ошибку. Ошибка гласит о том, что файл занят другим процессом, но я не понимаю каким, может я слепой, может недостаточно опыта. Буду рад, если поможете.
Функция:
public static void unzip(String source, String out) throws IOException {
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(source))) {
ZipEntry entry = zis.getNextEntry();
while (entry != null) {
File file = new File(out, entry.getName());
System.out.println("Разархивируем: " + entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
int bufferSize = Math.toIntExact(entry.getSize());
byte[] buffer = new byte[bufferSize > 0 ? bufferSize : 1];
int location;
while ((location = zis.read(buffer)) != -1) {
bos.write(buffer, 0, location);
}
}
}
entry = zis.getNextEntry();
}
zis.closeEntry();
}
File file = new File (source);
if (file.delete()) { //ТУТ ФАЙЛ ДОЛЖЕН УДАЛИТЬСЯ
System.out.println (file.getName ()+" deleted");
} else {
System.out.println (file.getName ()+" not deleted");
}
}
Вызов функции:
public static void getUpdate(String login, int ozu) {
new Thread(() -> {
try {
URL url = new URL("https://www.test/files/client_mc/client1165.zip");
HttpURLConnection updcon;
updcon = (HttpURLConnection) url.openConnection();
System.out.println(updcon);
File client = new File(util.getWorkDir().getAbsolutePath() + File.separator ,"client1165.zip");
long cll_web = updcon.getContentLength();
System.out.println(cll_web);
FileOutputStream fw = null;
if ((client.length() != cll_web) && cll_web > 1){
BufferedInputStream bis = new BufferedInputStream(updcon.getInputStream());
fw = new FileOutputStream(client);
byte[] by = new byte[1024];
int count = 0;
while ((count = bis.read(by)) != -1){
fw.write(by, 0, count);
System.out.println("Скачано " + ((int) client.length() / 1048576) + "Мбайт из " + (cll_web / 1048576) + "Мб");
}
unzip(util.getWorkDir().getAbsolutePath() + File.separator + "client1165.zip", util.getWorkDir().getAbsolutePath() + File.separator); // ВЫЗОВ ФУНКЦИИ
}
start_m(login, ozu);
} catch (IOException e) {
e.printStackTrace();
}
})
.start();
}
Ответы (1 шт):
Автор решения: Реинкарнация
→ Ссылка
Решил. Проблема была в моей невнимательности.
Я не закрыл fw(FileOutputStream) в главном потоке. Перед вызовом функции unzip() написал fw.close(), и всё заработало.
public static void getUpdate(String login, int ozu) {
new Thread(() -> {
try {
URL url = new URL("https://www.test/files/client_mc/client1165.zip");
HttpURLConnection updcon;
updcon = (HttpURLConnection) url.openConnection();
System.out.println(updcon);
File client = new File(util.getWorkDir().getAbsolutePath() + File.separator ,"client1165.zip");
long cll_web = updcon.getContentLength();
System.out.println(cll_web);
FileOutputStream fw = null;
if ((client.length() != cll_web) && cll_web > 1){
BufferedInputStream bis = new BufferedInputStream(updcon.getInputStream());
fw = new FileOutputStream(client);
byte[] by = new byte[1024];
int count = 0;
while ((count = bis.read(by)) != -1){
fw.write(by, 0, count);
System.out.println("Скачано " + ((int) client.length() / 1048576) + "Мбайт из " + (cll_web / 1048576) + "Мб");
}
fw.close(); // ЗАКРЫЛ СТРИМ
unzip(util.getWorkDir().getAbsolutePath() + File.separator + "client1165.zip", util.getWorkDir().getAbsolutePath() + File.separator);
}
start_m();
} catch (IOException e) {
e.printStackTrace();
}
})
.start();
}