Java压缩文件和目录到一个存档中

时间:2015-02-21 16:18:52

标签: java file directory compression zip

我有以下文件结构:

C:/test/example1/file1.txt
C:/test/file2.txt
C:/test/file3.txt

如何归档这些文件和目录,以便生成的zip看起来像这样:

Archive.zip
     example
          file1.txt
     file2.txt
     file3.txt

就像WinRar在选择要压缩的多个文件和文件夹时一样。

代码:

Path baseDir = Paths.get(content.toString());
Path zipPath = Paths.get(mainJarDir.toString());
Map<String, ?> env = Collections.singletonMap("create", "true");
URI uri = URI.create("jar:" + zipPath.toUri());

try {
  final FileSystem zipfs = FileSystems.newFileSystem(uri, env);
} 
catch (Exception e) {
  e.printStackTrace();
  try {
    MoreFiles.copyRecursive(baseDir, zipfs.get("/"), RecursionMode.FAIL_FAST, StandardCopyOption.REPLACE_EXISTING);
  } 
  catch (Exception ex) {
    ex.printStackTrace();
  }
}

1 个答案:

答案 0 :(得分:1)

这是使用one of my packages

完成的
final Path baseDir = Paths.get("c:\\test");

final Path zipPath = Paths.get("path/to/zipfile");
final Map<String, ?> env = Collections.singletonMap("create", "true");
final URI uri = URI.create("jar:" + zipPath.toUri());

try (
    final FileSystem zipfs = FileSystems.newFileSystem(uri, env);
) {
    // in java7-fs-more
    MoreFiles.copyRecursive(baseDir, zipfs.getPath("/"), RecursiveMode.FAIL_FAST);
}