简体   繁体   English

在Java中,如何使用Path对象复制目录中的所有文件?

[英]In Java, how to copy all the files in a directory using the Path object?

Please be kind, I'm new to Java. 请客气,我是Java的新手。 I'm looking for a way to copy all the files from a source directory to a target directory using the Path object. 我正在寻找一种使用Path对象将所有文件从源目录复制到目标目录的方法。 I looked around and saw older solutions to this problem (using the older java,io), but not the (newer java.nio) Path object. 我环顾四周,看到了针对此问题的较旧解决方案(使用较旧的java,io),但未看到(较新的java.nio)Path对象。 Here's what I have so far. 到目前为止,这就是我所拥有的。

// copyFiles - Copies files from source directory/folder to destination directory/folder
// Requires:
//      import java.nio.file.Path;
//      import java.nio.file.Paths;
//      import java.nio.file.Files;
public static void copyFiles(String OSType, String source, String destination)throws IOException {
    Path sourcePath = Paths.get(source);
    Path destinationPath = Paths.get(destination);

    if (!Files.exists(sourcePath) || !Files.isDirectory(sourcePath)) {
        System.out.println("Source directory/Folder " + source + " does not exists.");
    } else if (!Files.exists(destinationPath) || !Files.isDirectory(destinationPath)) {
        System.out.println("Destination directory/Folder " + source + " does not exists.");
    } else if (Files.list(sourcePath).count() > 0) {

        List<Path> sourceLocationContent = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(sourcePath)) {
            for (Path file : stream) {
            // System.out.println(file.getFileName());
            sourceLocationContent.add( file.getFileName());
        }

        System.out.println("sourceLocationContent.size() = " + sourceLocationContent.size());
        for (int i=0 ; sourceLocationContent.size() > i ; i++){
            System.out.println("sourceLocationContent.get("+i+") = " + sourceLocationContent.get(i));
            Files.copy(sourceLocationContent.get(i),destinationPath);
        }
    } catch (IOException | DirectoryIteratorException exception) {
        System.out.println(exception);
    }
} else {
    System.out.println("Source directory/Folder " + source + " is empty.");
}

} }

Here's my slightly long code that does this. 这是我稍长的代码来执行此操作。 The example can be run right away, just make sure to provide it src and dest directories. 该示例可以立即运行,只需确保提供src和dest目录即可。

    package copytodir;

import static java.nio.file.StandardCopyOption.*;
import java.nio.file.Path;
import java.nio.file.Files;
import java.io.*;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Chol
 */
public class CopyToDir {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter source: ");
        String srcDir = keyboard.nextLine();
        System.out.print("Enter destination: ");
        String destDir = keyboard.nextLine();
        copyDirectory(srcDir, destDir);
    }

    public static void copyDirectory(String sourceDir, String destDir) throws IOException {
        Path sourceDirPath = Paths.get(sourceDir);
        Path destDirPath = Paths.get(destDir);

        Files.copy(sourceDirPath, destDirPath, REPLACE_EXISTING);
        Files.list(sourceDirPath)
        .forEach(pathOfFile -> {
            try {
                copyFile(pathOfFile, Paths.get(destDirPath.toFile().getAbsolutePath() + File.separator + pathOfFile.toFile().getName()));
            } catch (IOException ex) {
                Logger.getLogger(CopyToDir.class.getName()).log(Level.SEVERE, null, ex);
            }
        });

    }

    public static void copyFile(Path srcFile, Path destFile) throws IOException {
        Files.copy(srcFile, destFile, REPLACE_EXISTING);
    }
}

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

相关问题 如何仅复制给定的文件而不是目录中的所有文件 - How to copy the given files only and not all the in the directory 如何复制远程目录中的所有文件? - How to copy all files inside a remote directory? 使用Java检索目录中文本文件的路径 - Retrieveing path of text files in Directory using Java 如何使用Java读取目录的所有文本文件的内容? - How to read the content of all of the text files of a directory using Java? 如何使用Java重命名Linux目录中的所有文件? - How to rename all files in a directory in linux using java? 如何使用 Java 解压缩目录中所有受密码保护的 zip 文件 - How to unzip all the password protected zip files in a directory using Java 如何复制png文件? 和动态目录路径 - How can i copy png files? and Dynamic directory path 如何在java中使用ProgressBar将文件从路径复制到路径 - how to Copy files from path to path with ProgressBar in java 使用 Java (Amazon S3) 将 all.txt 文件从一个 object 复制到另一个但在同一个存储桶中 - Copy all .txt files from one object to another but in the same bucket using Java (Amazon S3) 如何使用 Java NIO 将所有文件从源目录移动到目标目录,将现有文件保留在目标目录中? - How to move all files from source directory to destination directory, keeping existing files in destination directory, using Java NIO?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM