Home > Java > javaTutorial > How to Copy the First 20 Files from a Directory to a Subdirectory in Java?

How to Copy the First 20 Files from a Directory to a Subdirectory in Java?

DDD
Release: 2024-11-12 10:00:03
Original
496 people have browsed it

How to Copy the First 20 Files from a Directory to a Subdirectory in Java?

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

In this code:

  • We first obtain the source directory and create the subdirectory within it.
  • We then iterate over the first 20 files in the directory using a for loop.
  • For each file, we create the path to both the source and target files.
  • Finally, we use the Files.copy() method to copy the file to the subdirectory.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template