java - 即使关闭 InputStream 也无法删除文件

标签 java inputstream

读取文件后,我试图删除它,但出现以下错误:

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)

这是我的代码。我一直小心地在 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);”并且有效!

关于java - 即使关闭 InputStream 也无法删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54221659/

相关文章:

java - 如何在 gradle 中将 jacoco 代码覆盖级别设置为模块

java - 从 Java 代码调用 soapui 模拟服务?

java - HttpURLConnection返回的InputStream中的数据在读取之前存储在哪里?

Java InputStream读取多部分消息

java - Java套接字客户端未检测到服务器消息

java - 在运行时和编译时计算字符串

javascript - 为什么我无法读取在 POST 中收到的参数?

java - 什么时候应该使用安全注释 'denyAll'?

java - Scanner "not advance past any input"的 hasNext 方法如何?

c++ - 从包含特定字符串的行开始读取