2015-04-16 95 views
0

我跟着什麼this page告訴我,但我不能讓它工作。我需要它,以便在我的test.zip中有一個名爲「new」的文件夾。每當我運行下面的代碼時,它會給出一個FileAlreadyExistsException,並只創建一個空的zip文件。Java:如何使用java.nio.file.FileSystem創建一個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(); 
    } 
+0

修正了標題拼寫問題,刪除了文件系統標記,因爲這是預留到java庫文件系統而不是一般文件系統 –

回答

-2

您是否嘗試過使用java.util.zip.ZipEntry?

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

我想使用FileSystem的原因是因爲您可以追加到使用它的zip文件,據我所知ZipFile和ZipEntry不能這樣做。 – FOD

+1

那麼有[zipfilesystem](http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html)與FileSystem一起使用,但它是在java7中引入的 –

+0

這個問題並不是關於如何做到這一點,但特別是與新的nio API – for3st

1

javadoc

因爲Files.createDirectory()狀態拋出FileAlreadyExistsException - 如果目錄存在,但不是 目錄(可選具體的除外)

你需要檢查,如果已經在文件夾出口:

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