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

时间:2015-04-16 12:46:36

标签: java nio zipfile

我已按照this page告诉我的内容,但我无法让它工作。我想要它,以便在我的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();
    }

2 个答案:

答案 0 :(得分:3)

由于javadoc

中有Files.createDirectory()个州
  

抛出FileAlreadyExistsException - 如果dir存在但不是a   目录(可选的特定异常)

您需要检查文件夹是否已退出:

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

答案 1 :(得分:-3)

你试过java.util.zip.ZipEntry吗?

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