Java — How to move or rename a File or Directory | Code Factory

Java Move or Rename File using Files.move()

package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class MoveFileExample {
public static void main(String... args) {
Path sourceFilePath = Paths.get("folder/folder1/test.txt");
Path targetFilePath = Paths.get("folder/folder2/test.txt");
try {
Files.move(sourceFilePath, targetFilePath);
System.out.println("Done");
} catch (FileAlreadyExistsException ex) {
System.out.println("Target file already exists");
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
Files.move(sourceFilePath, targetFilePath, StandardCopyOption.REPLACE_EXISTING);
Path sourceFilePath = Paths.get("folder/folder1/test.txt");
Path targetFilePath = Paths.get("folder/folder1/test1.txt");
/* test.txt will be renamed to test1.text */
Files.move(sourceFilePath, targetFilePath);

Java move or rename a directory

package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class MoveDirectoryExample {
public static void main(String... args) {
Path sourceFilePath = Paths.get("folder/folder1/folder1.1");
Path targetFilePath = Paths.get("folder/folder2/folder1.1");
try {
Files.move(sourceFilePath, targetFilePath);
System.out.println("Done");
} catch (FileAlreadyExistsException ex) {
System.out.println("Target file already exists");
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store