English 中文(简体)
Apache Commons IO - FileUtils
  • 时间:2024-11-03

Apache Commons IO - FileUtils


Previous Page Next Page  

Provides method to manipulates files pke 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 −


pubpc class FileUtils
   extends Object

Features of FileUtils

The features of FileUtils are stated below −

    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 pst 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;

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

   pubpc 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.
Advertisements