In this example, I show you how to move or rename a file in Java using Files.move() API.
java.nio.file.Files.move() API
This method is used to move or rename a file to a target file.
By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same files, in which case this method has no effect.
Java Files.move() API Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaMoveFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/myfile.txt");
Path myPath2 = Paths.get("src/myfile2.txt");
Files.move(myPath, myPath2);
System.out.println("File moved");
}
}
Output:
File moved
The above example renames the "src/myfile.txt" file to "src/myfile2.txt".
Files.move() method takes two parameters: the source file path and the destination file path.
Files.move(myPath, myPath2);
Comments
Post a Comment
Leave Comment