• avi

    Apache Commons IO - FileUtils

    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 −

    public class FileUtils
       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 −

    Welcome to TutorialsPoint. Simply Easy Learning.

    IOTester.java

    import java.io.File;
    import java.io.IOException;
    import java.nio.charset.Charset;

    import org.apache.commons.io.FileUtils;

    public class IOTester {
       public static void main(String[] args) {
          try {
             //Using FileUtils
             usingFileUtils();
          } catch(IOException e) {
             System.out.println(e.getMessage());
          }
       }

       public static void usingFileUtils() throws IOException {
          //get the file object
          File file = FileUtils.getFile("input.txt");

          //get the temp directory
          File tmpDir = FileUtils.getTempDirectory();

          System.out.println(tmpDir.getName());

          //copy file to temp directory
          FileUtils.copyFileToDirectory(file, tmpDir);

          //create a new file
          File newTempFile = FileUtils.getFile(tmpDir, file.getName());

          //get the content
          String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());

          //print the content
          System.out.println(data);
       }
    }


    Output
    It will print the following result.

    Temp
    Welcome to TutorialsPoint. Simply Easy Learning.