gpt4 book ai didi

java - 创建和删除 zip 文件

转载 作者:行者123 更新时间:2023-11-29 04:10:44 29 4
gpt4 key购买 nike

我写了一个 JUnit 5 测试,我需要创建一个 zip 文件,在上面放一些文本文件,然后删除 zip 文件。

我在创建 zip 文件和其中的文本文件时没有任何问题,但每当我调用 file.delete() 时,它都会返回 false

我什至尝试创建一个空的 zip 文件,但它也无法删除它。有办法解决这个问题吗?

    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

}

最佳答案

如果您不创建太多临时文件,请使用 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.

文件系统操作可能不安全,例如Windows 喜欢锁定 JVM 进程使用的文件。

此外,您的测试代码可以在未正确关闭 ZipOutputStream 的情况下异常终止,这可能会锁定文件并防止删除。你应该使用finally:

ZipOutputStream out = null;
try {
out = ...
} finally {
if (out != null)
out.close();
}

关于java - 创建和删除 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55267715/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com