Create and delete a zip file

问题: I wrote a JUnit 5 test and I need to create a zip file, put some text files on it and remove the zip file. I don't have any problem for creating the zip file and the text...

问题:

I wrote a JUnit 5 test and I need to create a zip file, put some text files on it and remove the zip file.

I don't have any problem for creating the zip file and the text files inside it, but whenever I call file.delete() it returns false.

I even tried to create an empty zip file and it also fails to delete it. Is there a way to solve this ?

    static File file;

    @BeforeAll
    static void setUp() throws IOException {

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file=File.createTempFile("tempDir",".zip")));

        ZipEntry e = new ZipEntry("emptyFile.txt");
        out.putNextEntry(e);    
        out.closeEntry();    

        e = new ZipEntry("oneLineFile.txt");
        out.putNextEntry(e);

        StringBuilder sb;
        byte[] data;
        sb = new StringBuilder();
        sb.append("route_id,agency_id,route_short_name,route_long_name,route_type");
        data = sb.toString().getBytes();
        out.write(data, 0, data.length);

        out.closeEntry();

        out.close();
    }

    @AfterAll
    static void set(){

        file.delete(); // return false

    }

回答1:

If you don't create too many temporary files use File.deleteOnExit():

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. Files (or directories) are deleted in the reverse order that they are registered. Invoking this method to delete a file or directory that is already registered for deletion has no effect. Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification.

File system operations can be unsafe e.g. Windows likes to lock the files used by the JVM process.

Moreover your test code can terminate with exception without properly closing ZipOutputStream potentially locking the file and preventing deletion. You should use finally:

ZipOutputStream out = null;
try {
  out = ...
} finally {
  if (out != null) 
    out.close();
}
  • 发表于 2019-03-22 04:16
  • 阅读 ( 275 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除