java files

How to rename a file in java

public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

Note that the Files class defines the move method to move or rename a file in a platform independent manner.

Parameters:
dest – The new abstract pathname for the named file
Returns:
true if and only if the renaming succeeded; false otherwise
Throws:
SecurityException – If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to either the old or new pathnames
NullPointerException – If parameter dest is null

package com.candidjava.file;

import java.io.File;

public class RenameFile {
  public static void main(String[] args) {
    File oldname = new File("F:/Files/sample1.txt");
    File newname = new File("F:/Files/sample2.txt");
    boolean result = oldname.renameTo(newname);
    if (result) {
      System.out.println("File renamed successfully");
    } else {
      System.out.println("File rename failed");
    }
  }
}