java - 即使关闭 InputStream 也无法删除文件
问题描述
读取文件后,我试图将其删除,但出现以下错误:
java.io.IOException:无法在 org.apache.commons.io.FileUtils.cleanDirectory (FileUtils.java:1044) 中删除 org.apache.commons.io.FileUtils.forceDelete (FileUtils.java:1390) 中的文件 test.zip ) 在 org.apache.commons.io.FileUtils.deleteDirectory (FileUtils.java:977)
这是我的代码。我一直小心翼翼地在 finally 子句中关闭 InputStream,然后才调用删除文件的方法,但即便如此,我也只能在停止程序时删除它。
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);” 它有效!
推荐阅读
- linux - nohup 进程显示在 ps 中,但不在顶部
- python - 未正确调用 DataFrame 构造函数!matplotlib.pyplot 错误
- android - 在 Mapbox Android 中添加坐标
- c# - 使用条件运算符 (?:) 时,控制台将 char 显示为 int
- django - 如何将模态作为 Django 中另一个模态字段的数据类型?
- javascript - 更改 window.location.href 后无法返回
- cassandra-3.0 - cassandra datastax 驱动程序- session.execute() 和 cassandraTemplate.execute() 之间的区别
- oracle - Oracle - 使用 Left Join ON Where IS NULL 时性能不佳
- angular - Angular:在组件之间共享数据
- python - python列表:追加vs +=