2016-03-07 1 views
1

Так я использую код очень похожий на следующее (вытянут из http://fahdshariff.blogspot.com/2011/08/java-7-working-with-zip-files.html):Java ZipFileSystem атрибуты

/** 
* Creates/updates a zip file. 
* @param zipFilename the name of the zip to create 
* @param filenames list of filename to add to the zip 
* @throws IOException 
*/ 
public static void create(String zipFilename, String... filenames) 
    throws IOException { 

    try (FileSystem zipFileSystem = createZipFileSystem(zipFilename, true)) { 
    final Path root = zipFileSystem.getPath("/"); 

    //iterate over the files we need to add 
    for (String filename : filenames) { 
     final Path src = Paths.get(filename); 

     //add a file to the zip file system 
     if(!Files.isDirectory(src)){ 
     final Path dest = zipFileSystem.getPath(root.toString(), 
               src.toString()); 
     final Path parent = dest.getParent(); 
     if(Files.notExists(parent)){ 
      System.out.printf("Creating directory %s\n", parent); 
      Files.createDirectories(parent); 
     } 
     Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING); 
     } 
     else{ 
     //for directories, walk the file tree 
     Files.walkFileTree(src, new SimpleFileVisitor<Path>(){ 
      @Override 
      public FileVisitResult visitFile(Path file, 
       BasicFileAttributes attrs) throws IOException { 
      final Path dest = zipFileSystem.getPath(root.toString(), 
                file.toString()); 
      Files.copy(file, dest, StandardCopyOption.REPLACE_EXISTING); 
      return FileVisitResult.CONTINUE; 
      } 

      @Override 
      public FileVisitResult preVisitDirectory(Path dir, 
       BasicFileAttributes attrs) throws IOException { 
      final Path dirToCreate = zipFileSystem.getPath(root.toString(), 
                  dir.toString()); 
      if(Files.notExists(dirToCreate)){ 
       System.out.printf("Creating directory %s\n", dirToCreate); 
       Files.createDirectories(dirToCreate); 
      } 
      return FileVisitResult.CONTINUE; 
      } 
     }); 
     } 
    } 
    } 
} 

Когда я вызываю метод) в Files.copy() в visitFile (, то есть ЦСИ " rwxr-xr-x ', а dest успешно создан. Когда я разархивирую результат, соответствующий файл имеет только разрешения «rw-r-r--». Я попытался с помощью

Files.copy(src, dest, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING) 

но файл по-прежнему имеет «RW-R - r--» разрешения ... Выполнение Files.create() с «rwxr-хт-х» разрешения набор имеет тот же результат ... Есть идеи?

EDIT: Я попытался следующие, но я просто получить UnsupportedOperationException:

Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxr-xr-x"); 
Files.setPosixFilePermissions(dest, permissions); 
+0

Я заметил, что файлы, хранящиеся в 'ZipFileSystem', могут заменить существующие файлы. Реализация обновлений файлов в zfs не очень масштабируема - она ​​может кэшировать весь новый файл в памяти до закрытия zfs. –

ответ

1

ZIP file format по умолчанию не поддерживает Unix функции файловой системы. И ZIP filesystem provider, по крайней мере, не поддерживает сохранение разрешений Unix-файлов.

// ZIP created with teh Java zipfs 
zipinfo foobar.zip 

file system or operating system of origin:  MS-DOS, OS/2 or NT FAT 
version of encoding software:     2.0 
... 
non-MSDOS external file attributes:    000000 hex 
MS-DOS file attributes (00 hex):    none 

Если вы создадите ZIP-файл с версией Info-ZIP в Linux.

file system or operating system of origin:  Unix 
version of encoding software:     3.0 
... 
apparent file type:        text 
Unix file attributes (100755 octal):   -rwxr-xr-x 
MS-DOS file attributes (00 hex):    none 

Для получения дополнительной информации вы можете заглянуть в источник ZipFileSystem.javaoriginal source или от тока, включенных в JDK 8 Demos and Samples

редактировать Вы можете попробовать TrueVFS вместо zipfs. После быстрой проверки кажется, что он также не поддерживает разрешения файлов Unix.

Вы можете использовать Apache commons compress. После javadoc он поддерживает разрешения Unix.

из ZipArchiveEntry.setUnixMode

Устанавливает права доступа Unix в пути, понятном распакованного команды Info-Zip.

+0

Я понимаю, почему zip не поддерживает unix-специфические флаги, но это все еще ОЧЕНЬ раздражает ..... Знаете ли вы о каких-либо libs, которые поддерживают флаги unix-specific? – nterry