Copying Files to a Subdirectory within a Directory
In Java, copying files from one directory to another can be achieved using various approaches. To address your specific requirement of copying the first 20 files from a directory to its subdirectory, the following code can be employed:
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class DirectoryCopier { public static void main(String[] args) throws IOException { // Get the source directory File dir = new File("./source_directory"); // Create the subdirectory String subDirName = "subdirectory"; File subDir = new File(dir, subDirName); boolean success = subDir.mkdir(); // Iterate over the first 20 files in the directory int count = 0; for (File review : dir.listFiles()) { if (count == 20) { break; } // Copy the file to the subdirectory Path sourcePath = Paths.get(review.getAbsolutePath()); Path targetPath = Paths.get(subDir.getAbsolutePath(), review.getName()); Files.copy(sourcePath, targetPath); count++; } } }
In this code:
The above is the detailed content of How to Copy the First 20 Files from a Directory to a Subdirectory in Java?. For more information, please follow other related articles on the PHP Chinese website!