简体   繁体   English

需要使用 java 将所有文件从一个文件夹复制到另一个文件夹

[英]Need to copy all files from one folder to another using java

Src folder C:\temp源文件夹 C:\temp
Dest folder C:\temp1目标文件夹 C:\temp1

temp has one file (sample.csv)and temp1 folder is empty temp 有一个文件 (sample.csv) 并且 temp1 文件夹是空的

I need to copy sample.csv to temp1我需要将 sample.csv 复制到 temp1

Note: I cannot specify sample.csv anywhere in code as this name is dynamic.注意:我不能在代码中的任何地方指定 sample.csv,因为这个名称是动态的。

Path temp = Files.move(paths.get(src),patha.get(dest)).

This is working only if I give dummy file inside dest directory.仅当我在 dest 目录中提供虚拟文件时,这才有效。
C:\temp1\dummy.csv (i want to specify only C:\temp1 and src folder should go inside temp1) C:\temp1\dummy.csv(我只想指定 C:\temp1 和 src 文件夹应该在 temp1 中 go)

If you want to copy files from one directory to another one using plain java.nio , you could make use of a DirectoryStream .如果您想使用纯java.nio将文件从一个目录复制到另一个目录,您可以使用DirectoryStream

Here's some example:这是一些例子:

public static void main(String[] args) throws Exception {
    // define source and destination directories
    Path sourceDir = Paths.get("C:\\temp");
    Path destinationDir = Paths.get("C:\\temp1");
    
    // check if those paths are valid directories
    if (Files.isDirectory(sourceDir, LinkOption.NOFOLLOW_LINKS)
        && Files.isDirectory(destinationDir, LinkOption.NOFOLLOW_LINKS)) {
        // if they are, stream the content of the source directory
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(sourceDir)) {
            // handle each file in that stream 
            for (Path fso : ds) {
                /* 
                 * copy it to the destination, 
                 * that means resolving the file name to the destination directory
                 */
                Files.move(fso, destinationDir.resolve(fso.getFileName().toString()));
            }
        }
    }
}

You can add more checks, like checking if the directories are readable and actually exist.您可以添加更多检查,例如检查目录是否可读以及是否实际存在。 I just put the check for a directory here in order to show the possibilities of the Files class.我只是在这里检查一个目录,以显示Files class 的可能性。

Apache commons-io library has a FileUtils.copyDirectory() method. Apache commons-io 库有一个 FileUtils.copyDirectory FileUtils.copyDirectory()方法。 It copies all files from source dir and its subfolders to dest dir, creating dest dir if necessary.它将源目录及其子文件夹中的所有文件复制到目标目录,必要时创建目标目录。

FileUtils docs FileUtils 文档

If you are using Gradle, add this to your dependencies section to add this library to your project:如果您使用的是 Gradle,请将其添加到您的依赖项部分以将此库添加到您的项目中:

implementation 'commons-io:commons-io:2.11.0'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM