Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.

Class Declaration

Following is the declaration for org.apache.commons.io.FileUtils Class −

  1. public class FileUtils
  2. extends Object

Features

  • Methods to write to a file.
  • Methods to read from a file.
  • Methods to make a directory including parent directories.
  • Methods to copy files and directories.
  • Methods to delete files and directories.
  • Methods to convert to and from a URL.
  • Methods to list files and directories by filter and extension.
  • Methods to compare file content.
  • Methods to file last changed date.
  • Methods to calculating a checksum.

Example of FileUtils Class

Here is the input file we need to parse −

  1. Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.nio.charset.Charset;
  4.  
  5. import org.apache.commons.io.FileUtils;
  6.  
  7. public class IOTester {
  8. public static void main(String[] args) {
  9. try {
  10. //Using FileUtils
  11. usingFileUtils();
  12. } catch(IOException e) {
  13. System.out.println(e.getMessage());
  14. }
  15. }
  16.  
  17. public static void usingFileUtils() throws IOException {
  18. //get the file object
  19. File file = FileUtils.getFile("input.txt");
  20.  
  21. //get the temp directory
  22. File tmpDir = FileUtils.getTempDirectory();
  23.  
  24. System.out.println(tmpDir.getName());
  25.  
  26. //copy file to temp directory
  27. FileUtils.copyFileToDirectory(file, tmpDir);
  28.  
  29. //create a new file
  30. File newTempFile = FileUtils.getFile(tmpDir, file.getName());
  31.  
  32. //get the content
  33. String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());
  34.  
  35. //print the content
  36. System.out.println(data);
  37. }
  38. }

Output

It will print the following result.

  1. Temp
  2. Welcome to TutorialsPoint. Simply Easy Learning.