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 get free space of a drive or volume?

The getFreeSpaceKb(String path) method in the FileSystemUtils class can help you to calculate the free space of a drive or volume in kilobytes.

Beside using commons-io solution, you can use the File.getFreeSpace() method call provided in the Java 1.6 API. You can find an example of it in the following link: How do I get total space and free space of my disk?.

package org.kodejava.commons.io;

import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;

import java.io.IOException;

public class DiskFreeSpace {
    public static void main(String[] args) {
        try {
            String path = "F:/Temp";
            long freeSpaceKB = FileSystemUtils.freeSpaceKb(path);
            long freeSpaceMB = freeSpaceKB / FileUtils.ONE_KB;
            long freeSpaceGB = freeSpaceKB / FileUtils.ONE_MB;

            System.out.println("Size of " + path + " = " + freeSpaceKB + " KB");
            System.out.println("Size of " + path + " = " + freeSpaceMB + " MB");
            System.out.println("Size of " + path + " = " + freeSpaceGB + " GB");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

An example result of the code above is:

Size of F:/Temp = 323413052 KB
Size of F:/Temp = 315833 MB
Size of F:/Temp = 308 GB

Maven Dependencies

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

Maven Central

How do I read a file into byte array using Apache Commons IO?

The following example shows you how to read file contents into byte array. We use the IOUtils class of the Apache Commons IO library.

package org.kodejava.commons.io;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileToByteArray {
    public static void main(String[] args) {
        File file = new File("README.md");
        try {
            InputStream is = new FileInputStream(file);
            byte[] bytes = IOUtils.toByteArray(is);

            System.out.println("Byte array size: " + bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

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

Maven Central