Apache Commons-IO FileUtils in Java

The handling files with FileUtils from Apache Commons-IO in Java. The Apache Foundation has created a number of very useful data and file manipulation tools.

» See more examples

Remember that when creating our examples we use Maven and in the POM file we add this dependency.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.6</version>
</dependency>

The FileUtils class of the Commons-IO library will allow you to manipulate files in various ways, for example, to copy a file from one folder to another it is only necessary to use the copyFileToDirectory function. In this example we have a text file and we want to make a copy of it to the folder “subfolder”.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.geekole; // Name of your java package
import java.io.File;
import org.apache.commons.io.FileUtils;
/**
*
* @author geekole.com
*/
public class CopyFilesCommonsIO {
public static void main(String args[]) {
try {
File file1 = new File("/home/geekole/Documents/java/files/file1.txt");
File subfolder = new File("/home/geekole/Documents/java/files/subfolder/");
FileUtils.copyFileToDirectory(file1, subfolder);
System.out.println("Ready");
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.geekole; // Name of your java package import java.io.File; import org.apache.commons.io.FileUtils; /** * * @author geekole.com */ public class CopyFilesCommonsIO { public static void main(String args[]) { try { File file1 = new File("/home/geekole/Documents/java/files/file1.txt"); File subfolder = new File("/home/geekole/Documents/java/files/subfolder/"); FileUtils.copyFileToDirectory(file1, subfolder); System.out.println("Ready"); } catch (Exception e) { e.printStackTrace(); } } }
package com.geekole; // Name of your java package

import java.io.File;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author geekole.com
 */
public class CopyFilesCommonsIO {

    public static void main(String args[]) {
        try {
            File file1 = new File("/home/geekole/Documents/java/files/file1.txt");
            File subfolder = new File("/home/geekole/Documents/java/files/subfolder/");
            FileUtils.copyFileToDirectory(file1, subfolder);
            System.out.println("Ready");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If we run the example we get this result:

Apache Commons-IO FileUtils in Java

Only the file “file1.txt” is copied to the folder: /home/geekole/Documents/java/files/subfolder

Another very useful method is to copy the contents of one folder to another copyToDirectory.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.geekole; // Name of your java package
import java.io.File;
import org.apache.commons.io.FileUtils;
/**
*
* @author geekole.com
*/
public class CopyFoldersCommonsIO {
public static void main(String args[]) {
try {
File sourceDirectory= new File("/home/geekole/Documents/java/files");
File destinationDirectory = new File("/home/geekole/Documents/java/backupFiles");
FileUtils.copyToDirectory(sourceDirectory, destinationDirectory);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.geekole; // Name of your java package import java.io.File; import org.apache.commons.io.FileUtils; /** * * @author geekole.com */ public class CopyFoldersCommonsIO { public static void main(String args[]) { try { File sourceDirectory= new File("/home/geekole/Documents/java/files"); File destinationDirectory = new File("/home/geekole/Documents/java/backupFiles"); FileUtils.copyToDirectory(sourceDirectory, destinationDirectory); } catch (Exception e) { e.printStackTrace(); } } }
package com.geekole; // Name of your java package

import java.io.File;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author geekole.com
 */
public class CopyFoldersCommonsIO {

    public static void main(String args[]) {
        try {
            File sourceDirectory= new File("/home/geekole/Documents/java/files");
            File destinationDirectory = new File("/home/geekole/Documents/java/backupFiles");
            FileUtils.copyToDirectory(sourceDirectory, destinationDirectory);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

With the following result:

Apache Commons-IO FileUtils in Java

Copying the contents of /home/geekole/Documents/java/files recursively to /home/geekole/Documents/java/backupFiles/

FileUtils functions are especially useful:

String readFileToString(File file, Charset encoding) – Allows you to read the content of a text file and directly create a String.

public static void writeStringToFile(File file, String data, Charset encoding) – Allows you to create a text file with the content of a String that is passed as an argument along with its encoding.

But besides these simple examples, Apache Commons-IO FileUtils in Java has other methods that can help you:
  • static String byteCountToDisplaySize(BigInteger size)
  • static String byteCountToDisplaySize(long size)
  • static Checksum checksum(File file, Checksum checksum)
  • static long checksumCRC32(File file)
  • static void cleanDirectory(File directory)
  • static boolean contentEquals(File file1, File file2)
  • static boolean contentEqualsIgnoreEOL(File file1, File file2, String charsetName)
  • static File[] convertFileCollectionToFileArray(Collection<File> files)
  • static void copyDirectory(File srcDir, File destDir)
  • static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate)
  • static void copyDirectory(File srcDir, File destDir, FileFilter filter)
  • static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)
  • static void copyDirectoryToDirectory(File srcDir, File destDir)
  • static void copyFile(File srcFile, File destFile)
  • static void copyFile(File srcFile, File destFile, boolean preserveFileDate)
  • static long copyFile(File input, OutputStream output)
  • static void copyFileToDirectory(File srcFile, File destDir)
  • static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate)
  • static void copyInputStreamToFile(InputStream source, File destination)
  • static void copyToFile(InputStream source, File destination)
  • static void copyURLToFile(URL source, File destination)
  • static void copyURLToFile(URL source, File destination, int connectionTimeout, int readTimeout)
  • static void deleteDirectory(File directory)
  • static boolean deleteQuietly(File file)
  • static boolean directoryContains(File directory, File child)
  • static void forceDelete(File file)
  • static void forceDeleteOnExit(File file)
  • static void forceMkdir(File directory)
  • static void forceMkdirParent(File file)
  • static File getFile(File directory, String… names)
  • static File getFile(String… names)
  • static File getTempDirectory()
  • static String getTempDirectoryPath()
  • static File getUserDirectory()
  • static String getUserDirectoryPath()
  • static boolean isFileNewer(File file, Date date)
  • static boolean isFileNewer(File file, File reference)
  • static boolean isFileNewer(File file, long timeMillis)
  • static boolean isFileOlder(File file, Date date)
  • static boolean isFileOlder(File file, File reference)
  • static boolean isFileOlder(File file, long timeMillis)
  • static boolean isSymlink(File file)
  • static Iterator<File> iterateFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)
  • static Iterator<File> iterateFiles(File directory, String[] extensions, boolean recursive)
  • static Iterator<File> iterateFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)
  • static LineIterator lineIterator(File file)
  • static LineIterator lineIterator(File file, String encoding)
  • static Collection<File> listFiles(File directory, String[] extensions, boolean recursive)
  • static Collection<File> listFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)
  • static void moveDirectory(File srcDir, File destDir)
  • static void moveDirectoryToDirectory(File src, File destDir, boolean createDestDir)
  • static void moveFile(File srcFile, File destFile)
  • static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir)
  • static void moveToDirectory(File src, File destDir, boolean createDestDir)
  • static FileInputStream openInputStream(File file)
  • static FileOutputStream openOutputStream(File file)
  • static FileOutputStream openOutputStream(File file, boolean append)
  • static byte[] readFileToByteArray(File file)
  • static String readFileToString(File file)
  • static String readFileToString(File file, Charset encoding)
  • static String readFileToString(File file, String encoding)
  • static List<String> readLines(File file)
  • static List<String> readLines(File file, Charset encoding)
  • static List<String> readLines(File file, String encoding)
  • static long sizeOf(File file)
  • static BigInteger sizeOfAsBigInteger(File file)
  • static long sizeOfDirectory(File directory)
  • static BigInteger sizeOfDirectoryAsBigInteger(File directory)
  • static File toFile(URL url)
  • static File[] toFiles(URL[] urls)
  • static void touch(File file)
  • static URL[] toURLs(File[] files)
  • static boolean waitFor(File file, int seconds)
  • static void write(File file, CharSequence data)
  • static void write(File file, CharSequence data, boolean append)
  • static void write(File file, CharSequence data, Charset encoding)
  • static void write(File file, CharSequence data, Charset encoding, boolean append)
  • static void write(File file, CharSequence data, String encoding)
  • static void write(File file, CharSequence data, String encoding, boolean append)
  • static void writeByteArrayToFile(File file, byte[] data)
  • static void writeByteArrayToFile(File file, byte[] data, boolean append)
  • static void writeByteArrayToFile(File file, byte[] data, int off, int len)
  • static void writeByteArrayToFile(File file, byte[] data, int off, int len, boolean append)
  • static void writeLines(File file, Collection<?> lines)
  • static void writeLines(File file, Collection<?> lines, boolean append)
  • static void writeLines(File file, Collection<?> lines, String lineEnding)
  • static void writeLines(File file, Collection<?> lines, String lineEnding, boolean append)
  • static void writeLines(File file, String encoding, Collection<?> lines)
  • static void writeLines(File file, String encoding, Collection<?> lines, boolean append)
  • static void writeLines(File file, String encoding, Collection<?> lines, String lineEnding)
  • static void writeLines(File file, String encoding, Collection<?> lines, String lineEnding, boolean append)
  • static void writeStringToFile(File file, String data)
  • static void writeStringToFile(File file, String data, boolean append)
  • static void writeStringToFile(File file, String data, Charset encoding)
  • static void writeStringToFile(File file, String data, Charset encoding, boolean append)
  • static void writeStringToFile(File file, String data, String encoding)static void writeStringToFile(File file, String data, String encoding, boolean append)

We’ll be adding more examples of other Apache Commons-IO FileUtils in Java functions soon.