После прочтения файла я пытаюсь удалить его, но появляется следующая ошибка:
java.io.IOException: невозможно удалить файл test.zip по адресу
org.apache.commons.io.FileUtils.forceDelete (FileUtils.java:1390) в
org.apache.commons.io.FileUtils.cleanDirectory (FileUtils.java:1044)
в org.apache.commons.io.FileUtils.deleteDirectory
(FileUtils.java:977)
Вот мой код. Я был осторожен, чтобы закрыть InputStream в предложении finally и только потом вызывать метод, который удаляет файл, но даже тогда я могу удалить его только при остановке программы.
InputStream is = null;
try {
is = new URL(filePath).openStream(); // filePath is a string containing the path to the file like http://test.com/file.zip
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
String xml = sb.toString(); // this code is working, the result of the "xml" variable is as expected
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
removeFileAndFolder(absolutePath);
}
private void removeFileAndFolder(String absolutePath) {
new Thread(new Runnable() {
@Override
public void run() {
try {
String folder = getFolder(absolutePath); // this method just get the path to the folder, because I want to delete the entire folder, but the error occurs when deleting the file
FileUtils.deleteDirectory(new File(folder));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
После некоторых тестов я обнаружил, что могу вручную удалить файл непосредственно перед строкой «is = new URL (filePath) .openStream ();». После него и даже после строки "is.close ();" Я не могу удалить файл вручную, пока не остановлю программу.