Search in sources :

Example 1 with ZipCopyVisitor

use of cn.hutool.core.compress.ZipCopyVisitor in project hutool by looly.

the class ZipUtil method append.

/**
 * 在zip文件中添加新文件或目录<br>
 * 新文件添加在zip根目录,文件夹包括其本身和内容<br>
 * 如果待添加文件夹是系统根路径(如/或c:/),则只复制文件夹下的内容
 *
 * @param zipPath        zip文件的Path
 * @param appendFilePath 待添加文件Path(可以是文件夹)
 * @param options        拷贝选项,可选是否覆盖等
 * @throws IORuntimeException IO异常
 * @since 5.7.15
 */
public static void append(Path zipPath, Path appendFilePath, CopyOption... options) throws IORuntimeException {
    try (FileSystem zipFileSystem = FileSystemUtil.createZip(zipPath.toString())) {
        if (Files.isDirectory(appendFilePath)) {
            Path source = appendFilePath.getParent();
            if (null == source) {
                // 如果用户提供的是根路径,则不复制目录,直接复制目录下的内容
                source = appendFilePath;
            }
            Files.walkFileTree(appendFilePath, new ZipCopyVisitor(source, zipFileSystem, options));
        } else {
            Files.copy(appendFilePath, zipFileSystem.getPath(PathUtil.getName(appendFilePath)), options);
        }
    } catch (FileAlreadyExistsException ignored) {
    // 不覆盖情况下,文件已存在, 跳过
    } catch (IOException e) {
        throw new IORuntimeException(e);
    }
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) ZipCopyVisitor(cn.hutool.core.compress.ZipCopyVisitor) IORuntimeException(cn.hutool.core.io.IORuntimeException) FileSystem(java.nio.file.FileSystem) IOException(java.io.IOException)

Aggregations

ZipCopyVisitor (cn.hutool.core.compress.ZipCopyVisitor)1 IORuntimeException (cn.hutool.core.io.IORuntimeException)1 IOException (java.io.IOException)1 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)1 FileSystem (java.nio.file.FileSystem)1 Path (java.nio.file.Path)1