如何在Java中使用FileUtils移動檔案?
使用File類
java.io包中的名為File的類表示系統中的檔案或目錄(路徑名)。此類提供各種方法來對檔案/目錄執行各種操作。
此類提供各種方法來操作檔案,File類的rename()方法接受一個表示目標檔案的字串,並將當前檔案的抽象檔案路徑重新命名為給定的路徑。
此方法實際上將檔案從源路徑移動到目標路徑。
示例
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類,它包含對檔案、目錄或其他型別的檔案進行操作的(靜態)方法。
此類的move方法分別接受兩個路徑物件source和destination(以及一個可變引數來指定移動選項),並將source路徑表示的檔案移動到destination路徑。
示例
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 . . . . . . .
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP