Copying Files to Subdirectories in Java
Question:
How can I copy files from a directory into a subdirectory within the same directory using Java? I wish to iterate through the first 20 files in a directory, copying them to a newly created subdirectory named "trainingData."
Answer:
While Java does not natively provide a function for this specific task, a third-party library can efficiently resolve it. The Apache Commons IO library offers the FileUtils class with a method called copyDirectory.
Code Example:
import org.apache.commons.io.FileUtils; File sourceDirectory = new File("path/to/sourceDirectory"); File destinationDirectory = new File("path/to/sourceDirectory/trainingData"); try { FileUtils.copyDirectory(sourceDirectory, destinationDirectory); } catch (IOException e) { e.printStackTrace(); }
This code will copy all files and subdirectories within the sourceDirectory to the destinationDirectory. The trainingData directory must be created beforehand.
The above is the detailed content of How to Copy Files to a Subdirectory in Java?. For more information, please follow other related articles on the PHP Chinese website!