Commons Io 简明教程

Apache Commons IO - FileUtils

提供操作文件的方法,例如移动、打开、检查是否存在、读取文件等。这些方法使用 File Object。

Class Declaration

下面是 org.apache.commons.io.FileUtils 类的声明 -

public class FileUtils
   extends Object

Features of FileUtils

以下为 FileUtils 的特性 -

  1. 写入文件的方法。

  2. 从文件读取的方法。

  3. 生成目录(包括父目录)的方法。

  4. 复制文件和目录的方法。

  5. 删除文件和目录的方法。

  6. 转换为 URL 和从 URL 转换的方法。

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

  8. 比较文件内容的方法。

  9. 获取文件上次更改日期的方法。

  10. 计算校验和的方法。

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

Output

它将打印以下结果。

Temp
Welcome to TutorialsPoint. Simply Easy Learning.