使用 Java 從一個目錄移動檔案到另一個目錄
我們可以使用 Files.move() API 從一個目錄移動檔案到另一個目錄。以下是 move 方法的語法。
public static Path move(Path source,Path target,CopyOption... options) throws IOException
其中
source - 要移動的檔案的源路徑
target - 要移動的檔案的目標路徑
options - 選項,如 REPLACE_EXISTING、ATOMIC_MOVE
示例
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Tester {
public static void main(String[] args) {
//move file from D:/temp/test.txt to D:/temp1/test.txt
//make sure that temp1 folder exists
moveFile("D:/temp/test.txt", "D:/temp1/test.txt");
}
private static void moveFile(String src, String dest ) {
Path result = null;
try {
result = Files.move(Paths.get(src), Paths.get(dest));
} catch (IOException e) {
System.out.println("Exception while moving file: " + e.getMessage());
}
if(result != null) {
System.out.println("File moved successfully.");
}else{
System.out.println("File movement failed.");
}
}
}輸出
File moved successfully.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP