Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Moving a file from one directory to another using Java
We can use Files.move() API to move file from one directory to another. Following is the syntax of the move method.
public static Path move(Path source,Path target,CopyOption... options) throws IOException
Where
source − Source path of file to be moved
target − Target path of file to be moved
options − options like REPLACE_EXISTING, ATOMIC_MOVE
Example
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.");
}
}
}
Output
File moved successfully.
Advertisements
