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

How to Copy Files to a Subdirectory in Java?

Barbara Streisand
Release: 2024-11-08 06:11:01
Original
1088 people have browsed it

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();
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template