java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to rename a file or directory?

package com.javacoderanch.sample.java.io;

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

public class FileRenameExample
{
    public static void main(String[] args) throws IOException
    {
        // This will create a new file called OldHouses.csv
        File oldFile = new File("OldHouses.csv");
        oldFile.createNewFile();
        
        // Here we create a new instance of File that we gonna use
        // to rename the old file to the new one.
        File newFile = new File("NewHouses.csv");

        // The renameTo() method renames file or directory to a
        // new name by passing the new destination file.
        oldFile.renameTo(newFile);
    }
}