[英]How to copy specific files from one directory to another in Java
I have a directory with a bunch of files that i need to copy to another directory, Using Java i would only like to copy the files that end with a ".txt" extension.我有一个包含一堆文件的目录,我需要将其复制到另一个目录,使用 Java 我只想复制以“.txt”扩展名结尾的文件。 I'm familiar with doing it for one file as shown below, please could you help me do this as a loop to see which files in the source directory match with a "txt" extension and then copy them all over to a new directory.我熟悉如下所示为一个文件执行此操作,请你帮我循环执行此操作,以查看源目录中的哪些文件与“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();
}
You can use Files#list(Path)
to obtain a stream and use stream operations to filter and collect only those file names that contain the extension txt .您可以使用Files#list(Path)
获取 stream 并使用 stream 操作来过滤和仅收集那些包含扩展名的文件名txt 。 For example:例如:
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());
}
For me, this prints out:对我来说,这打印出来:
C:\Users\hecto\Documents\file1.txt
C:\Users\hecto\Documents\file2.txt
C:\Users\hecto\Documents\file3.txt
Even though I have other files and folders in that directory即使我在该目录中还有其他文件和文件夹
Using that, I came up with this solution to copy over those filtered files from their current location to a new destination and preserving the original names (Using Java 8 or above):使用它,我想出了这个解决方案,将那些过滤后的文件从当前位置复制到新目的地并保留原始名称(使用 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);
}
}
(Answer updated to use try-with-resources to close the stream) (答案更新为使用try-with-resources关闭流)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.