Java sort files in folders

In this example we will see how to sort files in folders. We will provide two folders one for input and one for output. Then we will filter only specific files (.png and .jpg) from input folder with method listFiles. After that we will loop over the files and read the date from each file. Then we will create folder with the name of the date. In the end we will copy the file to the respected folder.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;

public class Main {

    public static void main(String[] args) {
        // Change these values to match the directory containing the image files
        File inputDir = new File("/home/monster/Temp/picture_source");
        // Change this value to the root folder where the image will be copied 
        File outputDir = new File("/home/monster/Temp/picture_destination");

        // Get a list of all the PNG and JPG files in the input directory
        File[] files = inputDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".png")
                        || name.toLowerCase().endsWith(".jpg"));

        // Move the files to the output directory, preserving their original names
        for (File file : files) {

            String folderName = getFolderName(file);

            File outputSubDir = new File(outputDir + File.separator + folderName);
            // Create the output directory if it doesn't exist
            if (!outputSubDir.exists()) {
                outputSubDir.mkdirs();
            }
            File outputFile = new File(outputSubDir, file.getName());

            try {
                Files.copy(file.toPath(), outputFile.toPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Done!");
    }

    private static String getFolderName(File file) {

        SimpleDateFormat sd = new SimpleDateFormat("dd_MM_yyyy");
        BasicFileAttributes attrs = null;
        try {
            attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String res = sd.format(attrs.creationTime().toMillis());

        return res;
    }
}

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.