How to Rename File in Java

1. Overview

In this example, we will renameTo() method to rename a file.
Java comes with renameTo() method to rename a file. However, this method is really platform-dependent: you may successfully rename a file in *nix but failed in Windows. So, the return value (true if the file renames successful, false if failed) should always be checked to make sure the file is renamed successfully.

2. Rename File Example

  1. Create a file named "sample.txt" in directory "C:/workspace".
  2. Create File class object by passing file absolute location path "C:/workspace/sample.txt".
  3. We need to passs new abstract pathname to renameTo() method to rename the file.
  4. renameTo() method returns true if and only if the renaming succeeded; false otherwise.
  5. Observe the directory whether the file is renamed or not.
import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This Java program demonstrates how to rename existing file in Java.
 * @author javaguides.net
 */

public class RenameFileExample {
 private static final Logger LOGGER = LoggerFactory.getLogger(DeleteFileExample.class);

 public static void main(String[] args) {
  renameFile();
 }

 // Renames the file denoted by this abstract pathname.
 public static void renameFile() {
  File file = new File("C:/workspace/sample.txt");
  boolean hasRename = file.renameTo(new File("C:/workspace/sample2.txt"));
  if (hasRename) {
   LOGGER.info("File rename successful");
  } else {
   LOGGER.info("File reanme failed");
  }
 }
}
Simply copy paste the source code, it will work.

3. Reference

Comments