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);
}
}
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

PySpark on macOS: installation and use

Removing All Files Within a Git Branch

META STAKER

When and Why to Use := Over = in Python

Spotluck uses Stitch to eliminate their custom Python scripts and replicate their MongoDB data to…

Using the Unity Animation System

How To Describe Your Projects For PMP Application

Migrating our trusty ol’ .NET Framework applications to AWS, hold on! One foot at a time!

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
Code Factory

Code Factory

More from Medium

Access modifiers in java

Exception handling In Java.

Multithreading Concept in JAVA

Time Conversion | HackerRank Problem | Java Solution