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 provide 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 show you how to use the first two comparators listed above.

package org.kodejava.example.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.5</version>
</dependency>

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.example.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.5</version>
</dependency>

How to read text file contents line by line?

In the following code example you will learn how to read file contents line by line using the Apache Commons FileUtils.lineIterator() method. Reading file contents one line at a time, do some processing, and release it from memory immediately will lower the memory consumption used by your program.

The snippet below give you the basic usage of the FileUtils.lineIterator() method. You pass the file to read and the encoding to use. An Iterator of the lines in the file will be returned. Use the hasNext() method to see if there are lines to read from the iterator. The nextLine() method will give you the next line from the file.

When we finished with the iterator we need to close it using the LineIterator.close() or LineIterator.closeQuietly() method.

package org.kodejava.example.commons.io;

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

import java.io.File;
import java.net.URL;
import java.util.Objects;

public class ReadFileLineByLine {
    public static void main(String[] args) throws Exception {
        // Load file from resource directory.
        ClassLoader classLoader = ReadFileLineByLine.class.getClassLoader();
        URL url = Objects.requireNonNull(classLoader.getResource("data.txt"),
                "Resource could not be found.");

        File file = new File(url.getFile());
        LineIterator iterator = FileUtils.lineIterator(file, "UTF-8");
        try {
            while (iterator.hasNext()) {
                String line = iterator.nextLine();
                System.out.println("line = " + line);
            }
        } finally {
            LineIterator.closeQuietly(iterator);
        }
    }
}

In the example above we load the file from a resource directory. That’s why we use the ClassLoader.getResource() method. If you want to load a file from an absolute path you can simply create a File object and pass the absolute path to the file.

Maven Dependency

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

How do I sort files based on their last modified date?

This example demonstrates how to use Apache Commons IO LastModifiedFileComparator class to sort files based on their last modified date in ascending and descending order. There are two comparators defined in this class, the LASTMODIFIED_COMPARATOR and the LASTMODIFIED_REVERSE.

package org.kodejava.example.commons.io;

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

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

public class FileSortLastModified {
    public static void main(String[] args) {
        File dir = new File(System.getProperty("user.home"));
        File[] files = dir.listFiles();

        if (files != null) {
            // Sort files in ascending order based on file's last
            // modification date.
            System.out.println("Ascending order.");
            Arrays.sort(files, LASTMODIFIED_COMPARATOR);
            FileSortLastModified.displayFileOrder(files);

            System.out.println("------------------------------------");

            // Sort files in descending order based on file's last
            // modification date.
            System.out.println("Descending order.");
            Arrays.sort(files, LASTMODIFIED_REVERSE);
            FileSortLastModified.displayFileOrder(files);
        }
    }

    private static void displayFileOrder(File[] files) {
        for (File file : files) {
            System.out.printf("%2$td/%2$tm/%2$tY - %s%n", file.getName(),
                file.lastModified());
        }
    }
}

Here are the example results produced by the code snippet:

Ascending order.
15/12/2016 - ntuser.dat.LOG1
15/12/2016 - ntuser.ini
15/12/2016 - .m2
18/12/2016 - Contacts
22/12/2016 - Videos
01/01/2017 - VirtualBox VMs
02/01/2017 - Desktop
02/01/2017 - Documents
------------------------------------------
Descending order.
02/01/2017 - Documents
02/01/2017 - Desktop
01/01/2017 - VirtualBox VMs
22/12/2016 - Videos
18/12/2016 - Contacts
15/12/2016 - .m2
15/12/2016 - ntuser.ini
15/12/2016 - ntuser.dat.LOG1

Maven Dependencies

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

How do I create a copy of a file?

This example shows how we can use the Apache Commons IO library to simplify a file copy process.

package org.kodejava.example.commons.io;

import org.apache.commons.io.FileUtils;

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

public class FileCopyExample {
    public static void main(String[] args) {
        // The source file name to be copied.
        File source = new File("january.doc");

        // The target file name to which the source file will be copied.
        File target = new File("january-backup.doc");

        // A temporary folder where we are gonna copy the source file to.
        // Here we use the temporary folder of the OS, which can be
        // obtained using java.io.tmpdir property.
        File targetDir = new File(System.getProperty("java.io.tmpdir"));

        try {
            // Using FileUtils.copyFile() method to copy a file.
            System.out.println("Copying " + source + " file to " + target);
            FileUtils.copyFile(source, target);

            // To copy a file to a specified folder we can use the
            // FileUtils.copyFileToDirectory() method.
            System.out.println("Copying " + source + " file to " + targetDir);
            FileUtils.copyFileToDirectory(source, targetDir);
        } catch (IOException e) {
            // Errors will be reported here if any error occurs during 
            // copying the file
            e.printStackTrace();
        }
    }
}

How do I read file contents to string using Commons IO?

In this example we use FileUtils class from Apache Commons IO to read the content of a file. FileUtils have two static methods called readFileToString(File) and readFileToString(File, String) that we can use.

An example to read file contents and return the result as a string can be seen below.

package org.kodejava.example.commons.io;

import org.apache.commons.io.FileUtils;

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

public class ReadFileToStringSample {
    public static void main(String[] args) {
        // Here we create an instance of File for sample.txt file.
        File file = new File("sample.txt");

        try {
            // Read the entire contents of sample.txt
            String content = FileUtils.readFileToString(file);
            System.out.println("File content: " + content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}                                                                  

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
<dependencies>