Apache Commons IO - FileUtils

提供操作文件的方法,如移动,打开,检查存在,读取文件等.这些方法使用文件对象.

类声明

以下是 org.apache.commons.io.FileUtils Class :

public class FileUtils
   extends Object

功能

  • 写入的方法

  • 从文件中读取的方法.

  • 制作包含父目录的目录的方法.

  • 复制文件和目录的方法.

  • 删除文件和目录的方法.

  • 转换为URL的方法.

  • 按过滤器和扩展名列出文件和目录的方法.

  • 比较文件内容的方法.

  • 方法到文件最后更改日期.

  • 计算校验和的方法.

FileUtils示例Class

这是我们需要解析和减去的输入文件;

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);
   } 
}

输出

它将打印以下结果.

Temp
Welcome to TutorialsPoint. Simply Easy Learning.