是否可以使用 Java 中的 File 物件來更改目錄?


File 類

java.io 包中名為 File 的類表示系統中的檔案或目錄(路徑名稱)。此類提供了多種方法,用於對檔案/目錄執行各種操作。

此類提供了用於操作檔案的方法,**File** 類的 renameTo() 方法接受一個表示目標檔案並將其當前檔案的抽象檔案路徑重新命名為給定檔案路徑的字串。

此方法實際上將檔案從源路徑移動到目標路徑。

示例

import java.io.File;
public class MovingFile {
   public static void main(String args[]) {
      //Creating a source file object
      File source = new File("D:\source\sample.txt");
      //Creating a destination file object
      File dest = new File("E:\dest\sample.txt");
      //Renaming the file
      boolean bool = source.renameTo(dest);
      if(bool) {
         System.out.println("File moved successfully ........");
      }else {
         System.out.println("Unable to move the file ........");
      }
   }
}

輸出

File moved successfully . . . . . . .

Files 類

自 Java 7 引入 Files 類以來,它包含(靜態)方法,用於對檔案、目錄或其他型別的檔案進行操作。

此類的移動方法分別接受兩個路徑物件(源和目標)(以及一個可變引數來指定移動選項),並將源路徑表示的檔案移動到目標路徑。

示例

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MovingFile {
   public static void main(String args[]) throws Exception {
      //Creating a source Path object
      Path source = Paths.get("D:\source\sample.txt");
      //Creating a destination Path object
      Path dest = Paths.get("E:\dest\sample.txt");
      //copying the file
      Files.move(source, dest);
      System.out.println("File moved successfully ........");
   }
}

輸出

File moved successfully . . . . . . .

更新於: 2019 年 8 月 1 日

2K+ 瀏覽

開啟你的 職業 生涯

完成課程以獲取認證

開始
廣告
© . All rights reserved.