java - 即使我得到了正确的名称和路径,Zip 文件也没有被删除

标签 java delete-file

我试图在解压缩后删除一个 zip 文件。但我无法删除它:

if (file.getName().contains(".zip")) {
    System.out.println(file.getAbsolutePath()); // I am getting the correct path
    file.delete();
    System.out.println(file.getName()); // I am getting the correct name Script-1.zip
}

这是完整的代码

public class Zip4 {

    public static void main(String[] args) {
        File[] files = new File(args[0]).listFiles();

        for(File file : files)
        //  System.out.println(file.getName());
            //if(file.getName().contains("1400") && file.getName().contains(".zip"))
              extractFolder(args[0] + file.getName(), args[1]);
        DeleteFiles();

     //   for(File file : files)
                //  System.out.println("File:C:/1/"+ file.getName());

//      extractFolder(args[0]+file.getName(),args[1]);

    }

    private static void DeleteFiles()
    {
        File f = null;
        File[] paths;
        f = new File("D:/Copyof");
        paths = f.listFiles();

          for(File path:paths)
             {
                // prints file and directory paths
                if(path.getName().contains("J14_0_0RC") || path.getName().contains(".zip") || path.getName().contains(".log"))
                {

                     //System.out.println(path);
                     path.delete();
                }

             }
    }

    private static void extractFolder(String zipFile,String extractFolder) 
    {
        try
        {
            int BUFFER = 2048;
            File file = new File(zipFile);
            ZipFile zip = new ZipFile(file);
            String newPath = extractFolder;

            new File(newPath).mkdir();
            Enumeration zipFileEntries = zip.entries();

            // Process each entry
            while (zipFileEntries.hasMoreElements())
            {
                // grab a zip file entry
                ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
                String currentEntry = entry.getName();

                File destFile = new File(newPath, currentEntry);
                //destFile = new File(newPath, destFile.getName());
                File destinationParent = destFile.getParentFile();

                // create the parent directory structure if needed
                destinationParent.mkdirs();

                if (!entry.isDirectory())
                {
                    BufferedInputStream is = new BufferedInputStream(zip
                    .getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];

                    // write the current file to disk
                    FileOutputStream fos = new FileOutputStream(destFile);
                    BufferedOutputStream dest = new BufferedOutputStream(fos,
                    BUFFER);

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                    dest.flush();
                    dest.close();
                    fos.flush();
                    fos.close();
                    is.close();
                }

            }

            if(file.getName().contains(".zip"))
            {
                System.out.println(file.getAbsolutePath());
                file.delete();
                  System.out.println(file.getName());
            }
        }
        catch (Exception e) 
        {
            System.out.println("Error: " + e.getMessage());

        }
    }
}

最佳答案

ZipFile 是可关闭的资源。因此,要么在finally block 中完成后close()它,要么使用try-with-resources创建它(从java7开始):

try(ZipFile zip = new ZipFile(file)){
  //unzip here
}
file.delete();

除此之外,您应该重新访问此 block

dest.flush();
dest.close();
fos.flush();
fos.close();
is.close();

这很容易出现资源泄漏。如果上层调用之一失败,则后续所有调用都不会被调用,导致资源未关闭,造成资源泄漏。

所以最好也在这里使用try-with-resources

try(BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
    FileOutputStream fos = new FileOutputStream(destFile);
    BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
  //write the data
} //all streams are closed implicitly here

或者使用现有工具,例如 Apache Commons IO IOUtil.closeQuietly(resource) 或将每个调用嵌入

if(resource != null) {
  try{
     resource.close();
  } catch(IOException e){
     //omit
  }
}

您还可以省略对 flush() 的调用,该调用在关闭资源时隐式完成。

关于java - 即使我得到了正确的名称和路径,Zip 文件也没有被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37315806/

相关文章:

javascript - Sockets.io 连接,但不发送消息

java - 相同的计算流程,但功能不同

Windows命令提示符删除文件夹中的文件

java - 在 JUnit 中删除文件和目录

JavaFX TextFlow - 空文本节点不显示空(从相邻文本中窃取字符)

java - 具有延迟加载业务标识符的 Hibernate/JPA equals() 和 hashCode()

java - 换行符对计算机意味着什么

java - 使用 Java 代码删除 Android Q 中的非拥有文件

r - 删除R中制作的PDF文件