Java File renameTo() method with examples

April 28, 2020 No comments Java IO File Examples renameTo

1. Introduction

The renameTo() method renames the file and returns true if the operation was successful. This method is heavily platform-dependent. It might not be able to move the file from one filesystem to another.

2. Method signature

public boolean renameTo(File dest)

Parameters:

  • dest - the new abstract pathname for the named file

Returns

  • true - if the renaming file succeeded; false otherwise

Throws

  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. Snippet code that moves a file from path /tmp/exists.txt to /tmp/ttt/dest.txt

package com.frontbackend.java.io;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File source = new File("/tmp/exists.txt");
            File dest = new File("/tmp/ttt/dest.txt");

            System.out.println(dest.exists()); // false

            if (source.renameTo(dest)) {
                System.out.println("File renamed successfully");
            }

            System.out.println(source.exists()); // false
            System.out.println(dest.exists()); // true

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

false
File renamed successfully
false
true

4. Conclusion

In this article, we presented renameTo() method available in the Java IO API that could be used to rename and also move a file to another directory.

{{ message }}

{{ 'Comments are closed.' | trans }}