-
Notifications
You must be signed in to change notification settings - Fork 8
How to Rename File in Java
Ramesh Fadatare edited this page Jul 18, 2018
·
4 revisions
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 rename successful, false if failed) should always be checked to make sure the file is rename successful.
- Create a file named "sample.txt" in directory "C:/workspace".
- Create File class object by passing file absolute location path "C:/workspace/sample.txt".
- We need to passs new abstract pathname to renameTo() method to rename the file.
- renameTo() method returns true if and only if the renaming succeeded; false otherwise.
- 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.