Apache FileUtils Tutorial
java utils
This article is a quick tutorial on Apache FileUtils
, which is a part of Apache Commons IO
. FileUtils
is a
class with a bunch of static methods that perform common file-related operations.
My intention is not to cover all of the capabilities of this utility, but to focus on some of the most common
problems/use cases this solves. If you feel I’ve missed out on something you found to be useful, please do leave a
comment and I’ll make sure to add that.
Why FileUtils?
Let’s take the simple use case of reading a file. If we were to write our own method to read a file using FileReader
or BufferedReader
, it will look something like the following:
public static String readWithFileReader(String pathToFile) throws IOException {
String readData = "";
try (FileReader reader = new FileReader(pathToFile);
BufferedReader br = new BufferedReader(reader)) {
String line;
while ((line = br.readLine()) != null) {
readData += line;
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
return readData;
}
There are few things that can be better:
- For starters, that’s a lot of lines of code to accomplish something trivial
- The method will throw a
FileNotFoundException
if an invalid file path is passed. the client /caller of the method needs to ensure that the file exists, and the path is valid.
However, if we were to use a ibrary class like FileUtils
, your code will be a one-liner, and you get a lot of these
validations out of the box (whether a file path is valid, whether it is a directory, etc). You get a lot of these
features in the java NIO
library (which is available from JDK 7), and Google Common IO
as well.
Setup
First things first, FileUtils is not part of the Java standard library, so the commons-io
jar needs to be imported
to your project. You can add the following maven dependency to your pom.xml
get started:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
If Gradle is your preferred build tool, please add the following to your build.gradle
file:
compile group: 'commons-io', name: 'commons-io', version: '2.6'
If you would like to add a different version of the artifact, you can find them in mvn repo.
1. Write to file
One of the most common operations is to write to a file. With FileUtils
, you can do this with the following snippet
of code:
File file = new File("file.txt");
FileUtils.write(file, "Hello World!", "UTF-8");
One thing I like is that you can also append to a file using this method - You just need to pass the append
argument as true
.
FileUtils.write(file, "Hello World!", "UTF-8", true);
2. Read from file
Reading from a file is a one-liner as well 😄)
String fileContents = FileUtils.readFileToString(file, "UTF-8");
System.out.println(fileContents);
There are minor variants of this method, which are also quite handy:
readFileToByteArray
, which returns a byte[]
and readLines
, which returns a List<String>
3. Copy file
Another common use case is copying a file, which can be accomplished with the copyFile
method.
File fileCopy = new File("fileCopy.txt");
FileUtils.copyFile(file, fileCopy);
A similar use case is copying a file to a directory, which is done through the copyFileToDirectory
method.
You can also move(rename) a file using the renameFile
method, as long as the file you are renaming to does not
already exist.
4. Copy directory (recursively)
Copying a directory is pretty simple as well.
File srcDir = new File("src");
File destDir = new File("dest");
FileUtils.copyDirectory(srcDir, destDir);
A similar use case is copying a file to a directory, which is done through the copyDirectoryToDirectory
method.
You can also move(rename) a directory using the renameDirectory
method, as long as the file you are renaming to, does
not already exist.
5. Check for content equality
Checking if the contents of two files are equal is a typical use case. It can be accomplished through the diff
command from the command line, and there are tons of sites that let you compare text files (and a few common
file formats like PDFs). However, doing it programmatically is not hard either with FileUtils
.
// Expected to return true
FileUtils.contentEquals(file, fileCopy)
You can just use this in a loop if you want to compare multiple files. I cannot think of places where it would be
beneficial to use this instead of the diff
command and I’m not sure which option is more efficient (in terms of
performance, ability to handle large files, etc) - Please feel free to leave a comment if you have more insights on
this aspect.
6. Find checksum for a file
Last, but not the least, finding the checksum of a file can sometimes be handy and the checksumCRC32
and checksum
methods let you do this.
long checksumVal = FileUtils.checksumCRC32(file);
System.out.println(checksumVal);
The checksum
method accepts an object of a class that implements java.util.zip.Checksum
interface and uses that
object/algorithm to compute the checksum. The following is some sample code for the same:
Checksum checksumAlgo = new Adler32();
checksumVal = FileUtils.checksum(file, checksumAlgo).getValue();
System.out.println(checksumVal);
Conclusion
I’ll try to write an article comparing the features and performance of the different File I/O libraries(Apache
Commons IO, Java NIO, Google Common IO), if you are interested. Some
(small) features that FileUtils offers, and NIO does not is the method to copy contents of a directory and all of it
children (the copyDirectory
method explained above), and the method to generate a checksum for a file.
This pretty much sums up the neat little things you can carry out with Apache FileUtils. If you find any information to be incorrect or feel any other use case deserves to be here, please do let me know in the comments.