1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
public static void compressTarGzip(String dataPath, String dirName) throws IOException { Path source = Paths.get(dataPath); if (!Files.isDirectory(source)) { throw new IOException("请指定一个文件夹"); }
String tarFileName = dataPath + ".tar.gz"; logger.info("正在执行文件压缩: [{}]", dataPath); try (OutputStream fOut = Files.newOutputStream(Paths.get(tarFileName)); BufferedOutputStream buffOut = new BufferedOutputStream(fOut); GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(buffOut); TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) { Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
if (attributes.isSymbolicLink()) { return FileVisitResult.CONTINUE; }
Path targetFile = source.relativize(file); targetFile = Paths.get(dirName, targetFile.toString());
TarArchiveEntry tarEntry = new TarArchiveEntry( file.toFile(), targetFile.toString()); tOut.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); tOut.putArchiveEntry(tarEntry); Files.copy(file, tOut); tOut.closeArchiveEntry(); return FileVisitResult.CONTINUE; }
@Override public FileVisitResult visitFileFailed(Path file, IOException exc) { logger.error("无法对该文件压缩打包为tar.gz, {}", file, exc); return FileVisitResult.CONTINUE; } }); tOut.finish(); FileUtils.forceDelete(new File(dataPath)); logger.info("相关备份文件已压缩: [{}]", tarFileName); } }
public static void unCompressTarGzip(String file, String path) throws IOException { Path source = Paths.get(file + ".tar.gz"); Path target = Paths.get(path);
if (Files.notExists(source)) { throw new IOException("解压文件不存在"); } logger.info("正在执行文件解压: [{}]", file + ".tar.gz"); try (InputStream fi = Files.newInputStream(source); BufferedInputStream bi = new BufferedInputStream(fi); GzipCompressorInputStream gzi = new GzipCompressorInputStream(bi); TarArchiveInputStream ti = new TarArchiveInputStream(gzi)) {
ArchiveEntry entry; while ((entry = ti.getNextEntry()) != null) {
Path newPath = zipSlipProtect(entry, target);
if (entry.isDirectory()) { Files.createDirectories(newPath); } else { Path parent = newPath.getParent(); if (parent != null) { if (Files.notExists(parent)) { Files.createDirectories(parent); } } Files.copy(ti, newPath, StandardCopyOption.REPLACE_EXISTING); } } } logger.info("相关文件已解压完成,路径: [{}]", path); }
|