簡體   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