是否可以使用 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 . . . . . . .
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP