How to rename file using Java


Let us take a look at how to rename files in Java with examples of Java 7, 8, 9 and 11, and 17.

Example: Java 7
package org.code2care.java.examples;

import java.io.File;

public class FileRenameJava7 {

    public static void main(String[] args) {

        File oldFileName = new File("old_file.csv");
        File newFileName = new File("new_file.csv");

        if (oldFileName.renameTo(newFileName)) {
            System.out.println("File renamed successfully.");
        } else {
            System.out.println("Failed to rename the file.");
        }
    }
}

Example: Java 8, 9 or 11
package org.code2care.java.examples;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class FileRenameJava8 {

    public static void main(String[] args) throws IOException {

        Path oldFilePath = Path.of("old_file.csv");
        Path newFilePath = Path.of("new_file.csv");

        Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING);

        System.out.println("File renamed successfully.");
    }
}

Example: Java 17
package org.code2care.java.examples;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileRenameJava17 {

    public static void main(String[] args) throws IOException {

        Path oldFilePath = Path.of("old_file.csv");
        Path newFilePath = Path.of("new_file.csv");
        Path oldPath = Path.of("old.txt");
        Path newPath = Path.of("new.txt");

        Files.move(oldPath, newPath);

        System.out.println("File renamed successfully.");

    }
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap