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

时间:2019-01-16 16:46:11

标签: java inputstream

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

  

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)

这是我的代码。我一直很小心地在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();”行之后除非停止程序,否则无法手动删除文件。

2 个答案:

答案 0 :(得分:0)

也许我没有读懂你的问题,但是你写道:

  

// filePath是一个字符串,其中包含文件的路径,例如http://test.com/file.zip

因此,您要删除Web服务器上的文件(目录),而不要删除本地计算机或LAN上的文件吗?在这种情况下,您需要发出一些FTP命令(例如Apache FTP-client

最好的方法是从Apache Commons.net开始,并仅使用所需的部分(例如FTP / FTPS)。

import org.apache.commons.net.ftp.FTPClient;
[..]
FTPClient ftpClient = new FTPClient();    
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.deleteFile(fileToDelete);
ftpClient.logout();
ftpClient.disconnect();

答案 1 :(得分:0)

我明白了。我正在通过url(is = new URL(filePath).openStream();)打开文件,并尝试通过绝对路径将其删除。我将其更改为“ is = new FileInputStream(absoluteFilePath);”而且有效!

相关问题