繁体   English   中英

Java中如何将特定文件从一个目录复制到另一个目录

[英]How to copy specific files from one directory to another in Java

我有一个包含一堆文件的目录,我需要将其复制到另一个目录,使用 Java 我只想复制以“.txt”扩展名结尾的文件。 我熟悉如下所示为一个文件执行此操作,请你帮我循环执行此操作,以查看源目录中的哪些文件与“txt”扩展名匹配,然后将它们全部复制到一个新目录中。

File sourceFileLocation = new File(
                "C:\\Users\\mike\\data\\assets.txt");

        File newFileLocation = new File(
                "C:\\Users\\mike\\destination\\newFile.txt");
        try {
            Files.copy(sourceFileLocation.toPath(), newFileLocation.toPath());

        } catch (Exception e) {

            e.printStackTrace();
        }

您可以使用Files#list(Path)获取 stream 并使用 stream 操作来过滤和仅收集那些包含扩展名的文件名txt 例如:

List<Path> paths = Files.list(Paths.get("C:/Users/hecto/Documents")).filter(path -> path.toString().endsWith(".txt")).collect(Collectors.toList());
for (Path path : paths) {
    System.out.println(path.toString());
}

对我来说,这打印出来:

C:\Users\hecto\Documents\file1.txt
C:\Users\hecto\Documents\file2.txt
C:\Users\hecto\Documents\file3.txt

即使我在该目录中还有其他文件和文件夹在此处输入图像描述

使用它,我想出了这个解决方案,将那些过滤后的文件从当前位置复制到新目的地并保留原始名称(使用 Java 8 或更高版本):

try (Stream<Path> stream = Files.list(Paths.get("C:/Users/hecto/Documents"))) {
    List<Path> paths = stream.filter(path -> path.toString().endsWith(".txt")).collect(Collectors.toList());
    for (Path source : paths) {
        Path destination = Paths.get("C:/Users/hecto/Desktop/target" + File.separator + source.getFileName());
        Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
    }           
}

(答案更新为使用try-with-resources关闭流)

暂无
暂无

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

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