Easy Tutorial
❮ Java Hashmap Merge Arrays Find ❯

Java Example - File Renaming

Java Examples

The following example demonstrates how to rename a file using the oldName.renameTo(newName) method of the File class.

Before running the program, you need to create a test file named tutorialpro-test.txt in the current directory.

Main.java File

import java.io.File;
import java.io.IOException;

public class tutorialproTest {
    public static void main(String[] args) throws IOException {
        // Old file or directory
        File oldName = new File("./tutorialpro-test.txt");
        // New file or directory
        File newName = new File("./tutorialpro-test-2.txt");
        if (newName.exists()) {  // Ensure the new file name does not exist
            throw new java.io.IOException("file exists");
        }
        if(oldName.renameTo(newName)) {
            System.out.println("Renamed successfully");
        } else {
            System.out.println("Error");
        }
    }
}

The above code outputs the following result:

Renamed successfully

Java Examples

❮ Java Hashmap Merge Arrays Find ❯