How do I sort file names by their extension?

To sort file names by their extension, we can use the ExtensionFileComparator class from the Apache Commons IO library. This class provides a couple instances of comparator such as:

Comparator Description
EXTENSION_COMPARATOR Case sensitive extension comparator
EXTENSION_REVERSE Reverse case sensitive extension comparator
EXTENSION_INSENSITIVE_COMPARATOR Case insensitive extension comparator
EXTENSION_INSENSITIVE_REVERSE Reverse case insensitive extension comparator
EXTENSION_SYSTEM_COMPARATOR System sensitive extension comparator
EXTENSION_SYSTEM_REVERSE Reverse system sensitive path comparator

The following snippet shows you how to use the first two comparators listed above.

package org.kodejava.commons.io;

import org.apache.commons.io.FilenameUtils;

import static org.apache.commons.io.comparator.ExtensionFileComparator.*;

import java.io.File;
import java.util.Arrays;

public class FileSortByExtension {
    public static void main(String[] args) {
        File file = new File(".");

        // Excludes directory in the list
        File[] files = file.listFiles(File::isFile);

        if (files != null) {
            // Sort in ascending order.
            Arrays.sort(files, EXTENSION_COMPARATOR);
            FileSortByExtension.displayFileOrder(files);

            // Sort in descending order.
            Arrays.sort(files, EXTENSION_REVERSE);
            FileSortByExtension.displayFileOrder(files);
        }
    }

    private static void displayFileOrder(File[] files) {
        System.out.printf("%-20s | %s%n", "Name", "Ext");
        System.out.println("--------------------------------");
        for (File file : files) {
            System.out.printf("%-20s | %s%n", file.getName(),
                    FilenameUtils.getExtension(file.getName()));
        }
        System.out.println();
    }
}

The result of the code snippet:

Name                 | Ext
--------------------------------
README               | 
lipsum.doc           | doc
lipsum.docx          | docx
data.html            | html
contributors.txt     | txt
pom.xml              | xml

Name                 | Ext
--------------------------------
pom.xml              | xml
contributors.txt     | txt
data.html            | html
lipsum.docx          | docx
lipsum.doc           | doc
README               | 

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

How do I sort files and directories based on their size?

In this example, you will learn how to sort files and directories based on their size. Using the Apache Commons IO, we can utilize the SizeFileComparator class. This class provides some instances to sort file size such as:

Comparator Description
SIZE_COMPARATOR Size comparator instance – directories are treated as zero size
SIZE_REVERSE Reverse size comparator instance – directories are treated as zero size
SIZE_SUMDIR_COMPARATOR Size comparator instance which sums the size of a directory’s contents
SIZE_SUMDIR_REVERSE Reverse size comparator instance which sums the size of a directory’s contents

Now let’s jump to the code snippet below:

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Arrays;

import static org.apache.commons.io.comparator.SizeFileComparator.*;

public class FileSortBySize {
    public static void main(String[] args) {
        File dir = new File(".");
        File[] files = dir.listFiles();

        if (files != null) {
            // Sort files in ascending order based on file size.
            System.out.println("Ascending order.");
            Arrays.sort(files, SIZE_COMPARATOR);
            FileSortBySize.displayFileOrder(files, false);

            // Sort files in descending order based on file size
            System.out.println("Descending order.");
            Arrays.sort(files, SIZE_REVERSE);
            FileSortBySize.displayFileOrder(files, false);

            // Sort files in ascending order based on file / directory
            // size
            System.out.println("Ascending order with directories.");
            Arrays.sort(files, SIZE_SUMDIR_COMPARATOR);
            FileSortBySize.displayFileOrder(files, true);

            // Sort files in descending order based on file / directory
            // size
            System.out.println("Descending order with directories.");
            Arrays.sort(files, SIZE_SUMDIR_REVERSE);
            FileSortBySize.displayFileOrder(files, true);
        }
    }

    private static void displayFileOrder(File[] files, boolean displayDirectory) {
        for (File file : files) {
            if (!file.isDirectory()) {
                System.out.printf("%-25s - %s%n", file.getName(),
                        FileUtils.byteCountToDisplaySize(file.length()));
            } else if (displayDirectory) {
                long size = FileUtils.sizeOfDirectory(file);
                String friendlySize = FileUtils.byteCountToDisplaySize(size);
                System.out.printf("%-25s - %s%n", file.getName(),
                        friendlySize);
            }
        }
        System.out.println("------------------------------------");
    }
}

In the code snippet above we use a couple method from the FileUtils class such as the FileUtils.sizeOfDirectory() to calculate the size of a directory and FileUtils.byteCountToDisplaySize() to create human-readable file size.

The result of the code snippet:

Ascending order.
.editorconfig             - 389 bytes
kodejava.iml              - 868 bytes
pom.xml                   - 1 KB
------------------------------------
Descending order.
pom.xml                   - 1 KB
kodejava.iml              - 868 bytes
.editorconfig             - 389 bytes
------------------------------------
Ascending order with directories.
.editorconfig             - 389 bytes
src                       - 851 bytes
kodejava.iml              - 868 bytes
pom.xml                   - 1 KB
apache-commons-example    - 8 KB
hibernate-example         - 29 KB
.idea                     - 85 KB
------------------------------------
Descending order with directories.
.idea                     - 85 KB
hibernate-example         - 29 KB
apache-commons-example    - 8 KB
pom.xml                   - 1 KB
kodejava.iml              - 868 bytes
src                       - 851 bytes
.editorconfig             - 389 bytes

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

How do I read text file content line by line to a List of Strings using Commons IO?

The following example show how to use the Apache Commons IO library to read a text file line by line to a List of String. In the code snippet below we will read the contents of a file called sample.txt using FileUtils class. We use FileUtils.readLines() method to read the contents line by line and return the result as a List of Strings.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class ReadFileToListSample {
    public static void main(String[] args) {
        // Create a file object of sample.txt
        File file = new File("README.md");

        try {
            List<String> contents = FileUtils.readLines(file, "UTF-8");

            // Iterate the result to print each line of the file.
            for (String line : contents) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

How do I create a java.io.File object from URL?

The code snippet below uses the FileUtils.toFile(URL) method that can be found in the Apache Commons IO library to convert a URL into a File. The url protocol should be file or else null will be returned.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class URLToFileObject {
    public static void main(String[] args) throws Exception {
        // FileUtils.toFile(URL url) convert from URL the File.
        String data = FileUtils.readFileToString(Objects.requireNonNull(
                        FileUtils.toFile(URLToFileObject.class.getResource("/data.txt"))),
                StandardCharsets.UTF_8);
        System.out.println("data = " + data);

        // Creates a URL with file protocol and convert it into a File object.
        File file = FileUtils.toFile(new URL("file:///D:/demo.txt"));
        data = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        System.out.println("data = " + data);
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

How do I move directory to another directory with its entire contents?

Below is an example to move one directory with all its child directory and files to another directory. We can use the FileUtils.moveDirectory() method to simplify the process.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class DirectoryMove {
    public static void main(String[] args) {
        String source = "F:/Temp/source";
        File srcDir = new File(source);

        String destination = "F:/Temp/target";
        File destDir = new File(destination);

        try {
            // Move the source directory to the destination directory.
            // The destination directory must not exist prior to the
            // move process.
            FileUtils.moveDirectory(srcDir, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central