Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
Apache Commons IO is a comprehensive library of utilities that helps Java developers handle input/output (I/O) operations more efficiently. As part of the Apache Commons project, Commons IO provides a set of easy-to-use tools to manage file and stream implementations, which are otherwise cumbersome and error-prone in Java.
This article explores the key features and practical applications of Apache Commons IO, demonstrating why it is a valuable addition to any Java developer's toolkit.
Apache Commons IO is designed to bridge the gap between low-level Java I/O classes and high-level operations that developers often need to perform. The latest release provides optimized utility classes and methods that simplify tasks such as reading from and writing to files, managing file systems, and handling data streams. Its primary goals are to improve code readability, reduce boilerplate code, and minimize the likelihood of errors.
File and Directory Utilities:
FileUtils
: This class offers static methods for common file operations like copying, moving, deleting, and reading files. For example, FileUtils.copyFile(File srcFile, File destFile)
simplifies the task of copying files.DirectoryWalker
: A utility that allows recursive traversal of directory structures, making it easy to process files in a directory tree.File Monitoring:
FileAlterationMonitor
: This class provides a simple mechanism to monitor changes in a file system. It can detect file creation, modification, and deletion events.Streams and Readers/Writers:
IOUtils
: This class contains static methods for working with streams, readers, and writers. Methods like IOUtils.copy(InputStream input, OutputStream output)
and IOUtils.toString(InputStream input, String encoding)
facilitate data transfer and conversion.EndianUtils
: Utilities to handle endian-specific data conversions, which are often required when dealing with binary data.File Filters:
SuffixFileFilter
, PrefixFileFilter
, WildcardFileFilter
) allow developers to easily filter files based on naming patterns, extensions, or other criteria.File Comparators:
File Manipulation: Commons IO simplifies file manipulation tasks. For instance, copying the contents of one directory to another can be done effortlessly:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class FileManipulator {
public static void main(String[] args) {
File srcDir = new File("/path/to/source");
File destDir = new File("/path/to/destination");
try {
// Copy contents from source directory to destination directory
FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class FileManipulator {
public static void main(String[] args) {
File srcDir = new File("/path/to/source");
File destDir = new File("/path/to/destination");
try {
// Copy contents from source directory to destination directory
FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reading and Writing Files: Reading the contents of a file into a String
:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileReadWriteExample {
public static void main(String[] args) {
File file = new File("/path/to/file.txt");
try {
// Read file content into a String
String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
System.out.println("File Content: " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileReadWriteExample {
public static void main(String[] args) {
File file = new File("/path/to/file.txt");
try {
// Read file content into a String
String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
System.out.println("File Content: " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writing a String
to a file:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileReadWriteExample {
public static void main(String[] args) {
File file = new File("/path/to/file.txt");
String content = "Hello, World!";
try {
// Write String content to the specified file
FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileReadWriteExample {
public static void main(String[] args) {
File file = new File("/path/to/file.txt");
String content = "Hello, World!";
try {
// Write String content to the specified file
FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
}
File Monitoring: Setting up a file monitor to watch for changes in a directory:
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
public class FileMonitorExample {
public static void main(String[] args) {
// Create an observer for the specified directory
FileAlterationObserver observer = new FileAlterationObserver(new File("/path/to/directory"));
// Add a listener to handle file create and delete events
observer.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
System.out.println("File created: " + file.getName());
}
@Override
public void onFileDelete(File file) {
System.out.println("File deleted: " + file.getName());
}
// Other override methods for file modification, etc.
});
// Set up the file alteration monitor
FileAlterationMonitor monitor = new FileAlterationMonitor(5000, observer);
try {
// Start the monitoring process
monitor.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
public class FileMonitorExample {
public static void main(String[] args) {
// Create an observer for the specified directory
FileAlterationObserver observer = new FileAlterationObserver(new File("/path/to/directory"));
// Add a listener to handle file create and delete events
observer.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
System.out.println("File created: " + file.getName());
}
@Override
public void onFileDelete(File file) {
System.out.println("File deleted: " + file.getName());
}
// Other override methods for file modification, etc.
});
// Set up the file alteration monitor
FileAlterationMonitor monitor = new FileAlterationMonitor(5000, observer);
try {
// Start the monitoring process
monitor.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
IronPDF for Java, developed and maintained by Iron Software, is a powerful library that enables software engineers to create, edit, and extract PDF content in Java, Kotlin, and Scala projects.
By combining IronPDF with Apache Commons IO, developers can efficiently handle file operations while leveraging advanced PDF generation features. This article demonstrates how to use these two libraries together to generate PDFs from URLs, HTML files, and HTML strings.
IronPDF for Java builds on the success of its .NET counterpart, offering extensive capabilities including:
Before you begin, ensure you have added the necessary dependencies for both IronPDF and Apache Commons IO to your project. Below are the Maven dependencies for these libraries:
pom.xml
<dependencies>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- IronPDF for Java -->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.3.1</version>
</dependency>
<!-- SLF4J Logger for IronPDF -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.3</version>
</dependency>
</dependencies>
<dependencies>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- IronPDF for Java -->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.3.1</version>
</dependency>
<!-- SLF4J Logger for IronPDF -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.3</version>
</dependency>
</dependencies>
This example demonstrates how to read content from a text file using Apache Commons IO and then generate a PDF with IronPDF.
Main.java
import com.ironsoftware.ironpdf.License;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.Settings;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
public class PdfFromTextFileExample {
public static void main(String[] args) {
try {
// Apply your IronPDF license key
License.setLicenseKey("YOUR-LICENSE-KEY");
// Set a log path for IronPDF logging
Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));
// Read text content from a file using Apache Commons IO
File textFile = new File("example.txt");
String textContent = FileUtils.readFileToString(textFile, StandardCharsets.UTF_8);
// Render the text content as a PDF
PdfDocument pdfFromTextContent = PdfDocument.renderHtmlAsPdf("<pre>" + textContent + "</pre>");
// Save the PdfDocument using IronPDF's saveAs method
pdfFromTextContent.saveAs(Paths.get("example.pdf"));
System.out.println("PDF generated and saved as example.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import com.ironsoftware.ironpdf.License;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.Settings;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
public class PdfFromTextFileExample {
public static void main(String[] args) {
try {
// Apply your IronPDF license key
License.setLicenseKey("YOUR-LICENSE-KEY");
// Set a log path for IronPDF logging
Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));
// Read text content from a file using Apache Commons IO
File textFile = new File("example.txt");
String textContent = FileUtils.readFileToString(textFile, StandardCharsets.UTF_8);
// Render the text content as a PDF
PdfDocument pdfFromTextContent = PdfDocument.renderHtmlAsPdf("<pre>" + textContent + "</pre>");
// Save the PdfDocument using IronPDF's saveAs method
pdfFromTextContent.saveAs(Paths.get("example.pdf"));
System.out.println("PDF generated and saved as example.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is a brief explanation of the above code:
Import necessary libraries:
Main method setup:
main
method to contain the execution logic.Set IronPDF license:
License.setLicenseKey("YOUR-LICENSE-KEY")
. A license is required to generate PDF documents.Set log path:
Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"))
.Read text file:
example.txt
as a UTF-8 encoded string. The readFileToString
method converts the file content to a String
.Render PDF:
PdfDocument.renderHtmlAsPdf("<pre>" + textContent + "</pre>")
.Save PDF:
example.pdf
using pdfFromTextContent.saveAs(Paths.get("example.pdf"))
.Completion message and exception handling:
IOException
by printing the stack trace for debugging.For more detailed information on IronPDF, please visit the documentation page. For further exploring the capabilities of IronPDF, please visit this code examples page.
Apache Commons IO is an invaluable library for Java developers dealing with file and stream operations. By integrating Apache Commons IO with IronPDF for Java, you can enhance your file-handling capabilities while generating PDFs. Together, these libraries provide a powerful solution for managing and generating PDFs in Java applications. Whether generating PDFs from text files, URLs, HTML files, or HTML strings, this approach ensures streamlined and effective PDF management in Java projects.
IronPDF offers a free trial. Download the library from here and give it a try!