Java Rename File - Jave Move File With Examples

Java Rename file or move file is a common IO operation. We can use File.renameTo(File dest) method for java rename file and java move file operations.

Java Rename File

File renameTo method returns true if file rename is successful, else it returns false.

Some of the rename operation behaviors are platform dependent. For example, it might fail if you move a file from one filesystem to another or if a file already exists with the same name at the destination directory.

In Mac OS, if the destination file already exists renameTo() override the existing file with the source file.

Java Move File

Moving a file is achieved by the renameTo() function itself. Moving a file doesn’t change file contents, just its directory location. A file complete path contains directory information with the file name, renameTo method is able to change the directory path too, hence move the file.

Java Rename File Example

Here is the example program showing different ways for java rename file or java move file.

RenameFileJava.java

We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent and it doesn’t throw IO exception if rename fails. That’s all for a quick java rename file and move file example.

Reference: API Doc

By admin

Leave a Reply