После прочтения файла пытаюсь удалить его, но появляется следующая ошибка:
java.io.IOException: Unable to delete file test.zip at org.apache.commons.io.FileUtils.forceDelete (FileUtils.java:1390) at org.apache.commons.io.FileUtils.cleanDirectory (FileUtils.java:1044) at 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 (); Я не могу удалить файл вручную, пока не остановлю программу.




Я понял. Я открывал файл по URL-адресу (is = new URL (filePath) .openStream ();) и пытался удалить его по абсолютному пути. Я изменил его на "is = new FileInputStream (absoluteFilePath);" и это работает!