我有一個包含一堆檔案的目錄,我需要將它們復制到另一個目錄,使用 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();
}
uj5u.com熱心網友回復:
您可以使用Files#list(Path)獲取流并使用流操作來過濾和收集僅包含擴展名的檔案名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關閉流)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/431337.html
