簡體   English   中英

Java:如何使用java.nio.file.FileSystem在zip中創建目錄

[英]Java: How to create a directory in a zip using java.nio.file.FileSystem

我已經遵循了該頁面告訴我的內容,但是無法正常工作。 我想要它,以便在我的test.zip中有一個名為“ new”的文件夾。 每當我運行下面的代碼時,它就會給出FileAlreadyExistsException並僅創建一個空的zip文件。

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    Path path = Paths.get("test.zip");
    URI uri = URI.create("jar:" + path.toUri());
    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        Path nf = fs.getPath("new/");
        Files.createDirectory(path);

    } catch (IOException e) {
        e.printStackTrace();
    }

因為Files.createDirectory()javadoc中聲明

拋出FileAlreadyExistsException如果dir存在但不是目錄(可選的特定異常)

您需要檢查文件夾是否已經退出:

try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
    Path nf = fs.getPath("new");
    if (Files.notExists(nf)) {
        Files.createDirectory(nf);
    }
}

您嘗試過java.util.zip.ZipEntry嗎?

FileOutputStream f = new FileOutputStream("test.zip");
ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f));
zip.putNextEntry(new ZipEntry("new/"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM