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.

ppackage org.kodejava.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("README.md");

        // The target file name to which the source file will be copied.
        File target = new File("README-BACKUP.md");

        // 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();
        }
    }
}

Maven Dependencies

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

Maven Central

How do I write string data to file?

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

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

public class WriteToFileExample {
    public static void main(String[] args) {
        try {
            // Here we'll write our data into a file called
            // output.txt, this is the output.
            File file = new File("output.txt");
            // We'll write the string below into the file
            String data = "Learn Java by Examples";

            // To write a file called the writeStringToFile
            // method which require you to pass the file and
            // the data to be written.
            FileUtils.writeStringToFile(file, data, "UTF-8");
        } 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 calculate directory size?

In this example we are going to use the Apache Commons IO library to get or calculate the total size of a directory. The FileUtils class provided by the Commons IO can help us to achieve this goal.

The first method that we can use is the FileUtils.sizeOfDirectory(), it calculates the size of a directory recursively. It takes a File object that represent a directory as parameter and returns long value. If the directory has security restriction this method return 0. A negative value returned when the directory size if bigger than Long.MAX_VALUE.

You can also use the FileUtils.sizeOfDirectoryAsBigInteger() method. This method return the result as BigInteger as the method name describe. As the first method, this method also return 0 when the directory has a security restriction.

Both of the methods described above return the directory size in bytes. If you want a more human-readable size you can utilize the FileUtils.byteCountToDisplaySize() method, it will convert the bytes value into something like 1 MB, 1 GB.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.math.BigInteger;

public class DirectorySizeSample {
    public static void main(String[] args) {
        // sizeOfDirectory
        File tempDir = new File("F:/Temp");
        long size = FileUtils.sizeOfDirectory(tempDir);
        System.out.println("TempDir size = " + size + " bytes");
        System.out.println("TempDir size = " +
                FileUtils.byteCountToDisplaySize(size));

        // sizeOfDirectoryAsBigInteger()
        File dropboxDir = new File("F:/Dropbox");
        BigInteger sizeBig = FileUtils.sizeOfDirectoryAsBigInteger(dropboxDir);
        System.out.println("DropboxDir size = " + sizeBig);
        System.out.println("DropboxDir size = " +
                FileUtils.byteCountToDisplaySize(sizeBig));
    }
}

The result of the code snippet above:

TempDir size = 892059058 bytes
TempDir size = 850 MB
DropboxDir size = 892059058
DropboxDir size = 850 MB

Maven Dependencies

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

Maven Central

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.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("README.md");

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

Maven Dependencies

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

Maven Central