Search in sources :

Example 1 with MoveVisitor

use of cn.hutool.core.io.file.visitor.MoveVisitor in project hutool by looly.

the class PathUtil method moveContent.

/**
 * 移动文件或目录内容到目标目录中,例如:
 * <ul>
 *     <li>moveContent("/usr/aaa/abc.txt", "/usr/bbb")结果为:"/usr/bbb/abc.txt"</li>
 *     <li>moveContent("/usr/aaa", "/usr/bbb")结果为:"/usr/bbb"</li>
 * </ul>
 *
 * @param src        源文件或目录路径
 * @param target     目标路径,如果为目录,则移动到此目录下
 * @param isOverride 是否覆盖目标文件
 * @return 目标文件Path
 * @since 5.7.9
 */
public static Path moveContent(Path src, Path target, boolean isOverride) {
    Assert.notNull(src, "Src path must be not null !");
    Assert.notNull(target, "Target path must be not null !");
    final CopyOption[] options = isOverride ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING } : new CopyOption[] {};
    // 自动创建目标的父目录
    mkParentDirs(target);
    try {
        return Files.move(src, target, options);
    } catch (IOException e) {
        if (e instanceof FileAlreadyExistsException) {
            // issue#I4QV0L@Gitee
            throw new IORuntimeException(e);
        }
        // 移动失败,可能是跨分区移动导致的,采用递归移动方式
        try {
            Files.walkFileTree(src, new MoveVisitor(src, target, options));
            // 移动后空目录没有删除,
            del(src);
        } catch (IOException e2) {
            throw new IORuntimeException(e2);
        }
        return target;
    }
}
Also used : FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) StandardCopyOption(java.nio.file.StandardCopyOption) CopyOption(java.nio.file.CopyOption) MoveVisitor(cn.hutool.core.io.file.visitor.MoveVisitor) IORuntimeException(cn.hutool.core.io.IORuntimeException) IOException(java.io.IOException)

Aggregations

IORuntimeException (cn.hutool.core.io.IORuntimeException)1 MoveVisitor (cn.hutool.core.io.file.visitor.MoveVisitor)1 IOException (java.io.IOException)1 CopyOption (java.nio.file.CopyOption)1 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)1 StandardCopyOption (java.nio.file.StandardCopyOption)1