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:
-------------------------------------------------------------------------------
RenameFileExample.java:
===============================
import java.io.File;
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..");
}
else{
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
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:
RenameFile.java:
==============================
import java.io.*;
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(System.in);
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) {
e.printStackTrace();
}
}
}
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- docs.oracle.com(More About java.nio.file.Files)- Click Here