如何使用Java代码将文件夹(包括子目录和文件)移动到新文件夹中

发布于 2024-10-21 18:04:59 字数 361 浏览 3 评论 0原文

任何人都可以帮我编写一个 Java 代码,将一个文件夹复制或移动到另一个文件夹中。

例如:
我有一个名为 temp 的文件夹,在 temp 内有一个文件夹 in-temp

我希望将我的 temp 文件夹复制或移动到名为 new temp 的新文件夹中,但使用 Java 代码。

我通过在 Google 上搜索得到了一个示例代码,它将文件夹的子目录和文件复制到新文件夹中,但正如我所说,我需要使用以下命令移动文件夹它的子文件夹到一个新文件夹中。

帮我解决这个问题。

谢谢。

Can anyone help me for a Java code which copy or move one folder as it is into another folder.

For example:
I have a folder named temp, inside temp I have a folder in-temp.

I want that my temp folder should be copied or moved into a new folder named new temp, but by using Java code.

I got an example code by searching on Google which copies the sub-directories and files of a folder into a new folder, but as I said I need to move a folder with it's sub-folder into a new folder.

Help me to resolve this.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

辞取 2024-10-28 18:04:59

您可以使用 apache-commons-io:

org.apache.commons.io.FileUtils.copyDirectory(File, File)

You can use apache-commons-io:

org.apache.commons.io.FileUtils.copyDirectory(File, File)
羁〃客ぐ 2024-10-28 18:04:59

对于大多数情况,特别是当源和目标位于同一文件系统(分别为驱动器)时,标准 java.nio Files.move(路径源、路径目标、CopyOption...选项) 命令(自 Java 7 起可用)正是您所需要的。但是,该命令在某些情况下失败,因此您必须诉诸/后备来复制和复制。递归删除目录(这种模式也可以在 commons-io 的 FileUtils.moveDirectory)。

这是我最近在 Spring Boot 项目中实现的一个辅助方法(作为使用本机和现有 spring 方法从项目堆栈中删除 commons-io 的努力的一部分):

public static Path move(Path source, Path target) throws IOException {

    if (Files.exists(target)) {
        throw new FileAlreadyExistsException(String.format("Destination '%s' already exists", target));
    }

    try {
        return Files.move(source, target);
    } catch (IOException ignored) {
        // you may want some logging here, or just ignore the exception
    }

    FileSystemUtils.copyRecursively(source, target);
    FileSystemUtils.deleteRecursively(source);
    return target;
}

两个 FileSystemUtils方法是 spring 框架的一部分,但是如果您没有基于 spring 的项目......它们的实现非常简单:)

我在下面记录它们,以下只是原始 源代码来自 Github

/**
 * Recursively copy the contents of the {@code src} file/directory
 * to the {@code dest} file/directory.
 * @param src the source directory
 * @param dest the destination directory
 * @throws IOException in the case of I/O errors
 * @since 5.0
 */
public static void copyRecursively(Path src, Path dest) throws IOException {
    Assert.notNull(src, "Source Path must not be null");
    Assert.notNull(dest, "Destination Path must not be null");
    BasicFileAttributes srcAttr = Files.readAttributes(src, BasicFileAttributes.class);

    if (srcAttr.isDirectory()) {
        Files.walkFileTree(src, EnumSet.of(FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Files.createDirectories(dest.resolve(src.relativize(dir)));
                return FileVisitResult.CONTINUE;
            }
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.copy(file, dest.resolve(src.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    else if (srcAttr.isRegularFile()) {
        Files.copy(src, dest);
    }
    else {
        throw new IllegalArgumentException("Source File must denote a directory or file");
    }
}

/**
 * Delete the supplied {@link Path} — for directories,
 * recursively delete any nested directories or files as well.
 * @param root the root {@code Path} to delete
 * @return {@code true} if the {@code Path} existed and was deleted,
 * or {@code false} if it did not exist
 * @throws IOException in the case of I/O errors
 * @since 5.0
 */
public static boolean deleteRecursively(@Nullable Path root) throws IOException {
    if (root == null) {
        return false;
    }
    if (!Files.exists(root)) {
        return false;
    }

    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }
        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }
    });
    return true;
}

这段代码效果很好 - 如果您不确定自己在看什么,那么您需要对 文件访问者 API – 这是一种非常强大的模式,可以出于多种目的有效地遍历目录(即获取文件夹大小、列出文件等)。

For most cases, specifically when source and target are on the same filesystem, respectively drive, the standard java.nio Files.move(Path source, Path target, CopyOption... options) command (available since Java 7) does exactly what you need. However, the command will fail in some cases, so you'd have to resort/fallback to to copy & delete the directory recursively (this pattern is also found in commons-io's FileUtils.moveDirectory).

This is a helper method that i just recently implemented in a Spring Boot project (as part of an effort to remove commons-io from the project's stack, using native & existing spring methods):

public static Path move(Path source, Path target) throws IOException {

    if (Files.exists(target)) {
        throw new FileAlreadyExistsException(String.format("Destination '%s' already exists", target));
    }

    try {
        return Files.move(source, target);
    } catch (IOException ignored) {
        // you may want some logging here, or just ignore the exception
    }

    FileSystemUtils.copyRecursively(source, target);
    FileSystemUtils.deleteRecursively(source);
    return target;
}

The two FileSystemUtils methods are part of the spring framework, but if you don't have a spring-based project… their implementations are pretty straightforward :)

I am documenting them here below, the following is just a copy from the original source code from Github.

/**
 * Recursively copy the contents of the {@code src} file/directory
 * to the {@code dest} file/directory.
 * @param src the source directory
 * @param dest the destination directory
 * @throws IOException in the case of I/O errors
 * @since 5.0
 */
public static void copyRecursively(Path src, Path dest) throws IOException {
    Assert.notNull(src, "Source Path must not be null");
    Assert.notNull(dest, "Destination Path must not be null");
    BasicFileAttributes srcAttr = Files.readAttributes(src, BasicFileAttributes.class);

    if (srcAttr.isDirectory()) {
        Files.walkFileTree(src, EnumSet.of(FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Files.createDirectories(dest.resolve(src.relativize(dir)));
                return FileVisitResult.CONTINUE;
            }
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.copy(file, dest.resolve(src.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    else if (srcAttr.isRegularFile()) {
        Files.copy(src, dest);
    }
    else {
        throw new IllegalArgumentException("Source File must denote a directory or file");
    }
}

/**
 * Delete the supplied {@link Path} — for directories,
 * recursively delete any nested directories or files as well.
 * @param root the root {@code Path} to delete
 * @return {@code true} if the {@code Path} existed and was deleted,
 * or {@code false} if it did not exist
 * @throws IOException in the case of I/O errors
 * @since 5.0
 */
public static boolean deleteRecursively(@Nullable Path root) throws IOException {
    if (root == null) {
        return false;
    }
    if (!Files.exists(root)) {
        return false;
    }

    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }
        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }
    });
    return true;
}

This code works great – if you're not sure what you're looking at here, then you'll want to develop a basic understanding of the File Visitor API – which is a really powerful pattern to efficiently traverse directories for a multitude of purposes (i.e. get folder size, list files, etc.).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文