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.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.11.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.11.0</version>
</dependency>

Maven Central

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.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());
        try (LineIterator iterator = FileUtils.lineIterator(file, "UTF-8")) {
            while (iterator.hasNext()) {
                String line = iterator.nextLine();
                System.out.println("line = " + line);
            }
        }
    }
}

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 Dependencies

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

Maven Central

How do I create File object from URL?

The code snippet below use the FileUtils.toFile(URL) method that can be found in the 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 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.11.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 call 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.12.0</version>
</dependency>

Maven Central

How do I copy directory with all its contents to another directory?

To copy a directory with the entire child directories and files we can use a handy method provided by the Apache Commons IO FileUtils.copyDirectory(). This method accept two parameters, the source directory and the destination directory. The source directory should be available while if the destination directory doesn’t exist it will be created.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

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

public class DirectoryCopy {
    public static void main(String[] args) {
        // An existing directory to copy.
        String source = "F:/Temp/source";
        File srcDir = new File(source);

        // The destination directory to copy to. This directory
        // doesn't exist and will be created during the copy
        // directory process.
        String destination = "F:/Temp/target";
        File destDir = new File(destination);

        try {
            // Copy source directory into destination directory
            // including its child directories and files. The
            // destination directory will be created if it does
            // not exist. This copy process also preserve the
            // date information of the file.
            FileUtils.copyDirectory(srcDir, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

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

Maven Central

How do I copy a URL into a file?

The code snippet below show you how to use the FileUtils.copyURLToFile(URL, File) method of the Apache Commons IO library to help you to copy the contents of a URL directly into a file.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class URLToFile {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.google.com");
            File destination = new File("google.html");

            // Copy bytes from the URL to the destination file.
            FileUtils.copyURLToFile(url, destination);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.12.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.12.0</version>
</dependency>

Maven Central

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

The following example shows you how to read file contents into byte array. We use the IOUtils class of the 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.11.0</version>
</dependency>

Maven Central

How do I get the content of an InputStream as a String?

We can use the code below to convert the content of an InputStream into a String. At first, we use FileInputStream create to a stream to a file that going to be read. IOUtils.toString(InputStream input, String encoding) method gets the content of the InputStream and returns a string representation of it.

package org.kodejava.commons.io;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;

public class InputStreamToString {
    public static void main(String[] args) throws Exception {
        // Create an input stream for reading data.txt file content.
        try (InputStream is = new FileInputStream("data.txt")) {
            // Get the content of an input stream as a string using UTF-8
            // as the character encoding.
            String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
            System.out.println(contents);
        }
    }
}

Maven Dependencies

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

Maven Central