Apache Commons IO - FileUtils



提供方法操縱檔案,例如移動、開啟、檢查是否存在、讀取檔案等。這些方法使用檔案物件。

類宣告

以下宣告適用於 **org.apache.commons.io.FileUtils** 類 -

public class FileUtils
   extends Object

FileUtils 的特性

以下列出 FileUtils 的特性:

  • 寫入檔案的方法。
  • 從檔案中讀取的方法。
  • 建立目錄(含父目錄)的方法。
  • 複製檔案和目錄的方法。
  • 刪除檔案和目錄的方法。
  • 轉換到 URL 和從 URL 轉換的方法。
  • 按過濾器和副檔名列出檔案和目錄的方法。
  • 比較檔案內容的方法。
  • 獲取檔案最後更改日期的方法。
  • 計算檢驗和的方法。

FileUtils 類的示例

以下是需要解析的輸入檔案 -

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.
廣告
© . All rights reserved.