HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
1. Feel Free to ask and submit anything on and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.

java-file-handling: How to rename a file in java at windows platform?

I tried many example found on other sites but every time i failed to rename file at windows. Please give me a working example to rename a file at windows platform.

java x 211
file-handling x 9
Posted On : 2015-08-18 15:46:34.0
profile Rishi Kumar - Rishi Kumar


I know you are trying to rename the file using renameTo(File) method. But this method is platform dependent. You may successfully rename a file in *nix but failed in Windows. So, the return value (true if the file rename successful, false if failed) should always be checked to make sure the file is renamed successfully.

Let´s first see the renameTo(File) method example:


public class RenameFileExample
public static void main(String[] args)

File oldfile =new File("oldfile.txt");
File newfile =new File("newfile.txt");

if(newfile.exists()) {
System.out.println("file already exists..");
System.out.println("Rename succesful");
System.out.println("Rename failed");

So above example will not work on windows. To rename file at windows platform we must use java.nio.file package classes. It provides classes and methods to perform file operation at windows platform. Let´s see a working example to rename a file at windows:
import java.util.Scanner;
import java.nio.file.*;

class RenameFile{
public static void main(String s1[]){
System.out.println("Enter the old file-name with its extension you want to rename:");
Scanner input=new Scanner(;
String oldName=input.nextLine();
Path source = new File(oldName).toPath();
System.out.println("Enter the new file-name with its extension:");
String newName=input.nextLine();
try {
Files.move(source, source.resolveSibling(newName));//rename the file in the same directory
System.out.println("File has been successfully renamed....");
} catch (IOException e) {

Usage Examples:>
Suppose we want to rename a file to "newname", keeping the file in the same directory:

Path source = ...
Files.move(source, source.resolveSibling("newname"));

Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:

Path source = ...
Path newdir = ...
Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING); Parameters:
source - the path to the file to move
target - the path to the target file (may be associated with a different provider to the source path)
options - options specifying how the move should be done.

Reference- About java.nio.file.Files)- Click Here

Posted On : 2015-08-18 16:05:33
Satisfied : 1 Yes  0 No
profile Garima Gupta - Garima Gupta
Reply This Thread

Post Answer
Please Login First to Post Answer: Login login with facebook -