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

Maven Central

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.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/2020 - ntuser.dat.LOG1
15/12/2020 - ntuser.ini
15/12/2020 - .m2
18/12/2020 - Contacts
22/12/2020 - Videos
01/01/2021 - VirtualBox VMs
02/01/2021 - Desktop
02/01/2021 - Documents
------------------------------------------
Descending order.
02/01/2021 - Documents
02/01/2021 - Desktop
01/01/2021 - VirtualBox VMs
22/12/20202 - Videos
18/12/20202 - Contacts
15/12/20202 - .m2
15/12/20202 - ntuser.ini
15/12/20202 - ntuser.dat.LOG1

Maven Dependencies

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

Maven Central

How do I search for files recursively using Apache Commons IO?

This example demonstrates how we can use the FileUtils class listFiles() method to search for a file specified by their extensions. We can also define to find the file recursively deep down into the subdirectories.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Collection;

public class SearchFileRecursive {
    public static void main(String[] args) {
        File root = new File("F:/Wayan/Kodejava/kodejava-example");

        try {
            String[] extensions = {"xml", "java", "dat"};

            // Find files within a root directory and optionally its
            // subdirectories, which match an array of extensions. When the
            // extensions are null, all files will be returned.
            //
            // This method will return matched file as java.io.File
            Collection<File> files = FileUtils.listFiles(root, extensions, true);

            for (File file : files) {
                System.out.println("File = " + file.getAbsolutePath());
            }
        } catch (Exception 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 touch a file using Apache Commons IO?

This example demonstrates a touch command just like Unix touch command. If the file to be touched doesn’t exist, a new empty file will be created.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

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

public class TouchFileExample {
    public static void main(String[] args) {
        try {
            File file = new File("Touch.dat");

            // Touch the file. When the file does not exist, a new file will be
            // created. If the file exists, change the file timestamp.
            FileUtils.touch(file);
        } 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 delete directory recursively?

Using the FileUtils.deleteDirectory() from the Apache Commons IO library, we can simplify the process of deleting directory and everything below it recursively.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

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

public class DeleteDirectory {
    public static void main(String[] args) {
        try {
            File directory = new File("F:/Temp");

            // Deletes a directory recursively. When a deletion process is failed, an
            // IOException will be thrown; that's why we catch the exception.
            FileUtils.deleteDirectory(directory);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

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

Maven Central