Home  >  Article  >  Java  >  How to Copy Files to a Subdirectory in Java?

How to Copy Files to a Subdirectory in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 06:11:01992browse

How to Copy Files to a Subdirectory in Java?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn