How to rename a file ( Change file name) in java?

DeeKay October 3, 2011 at 11:06 pm · java.io

Below java code shows how to rename a file or change a file name

/****************************************************************************************
 * Created on 10-2011Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

import java.io.File;

/**
 * Created by http://kodehelp.com
 * Date: 10/3/11
 */
public class RenameFile {
    public static void main(String args[]){
        File file = new File("/conf.txt");

        if (!file.exists() || file.isDirectory()) {
            System.out.println("File does not exist: " + file);
            return;
        }

        File newFile = new File("/conf.ini");

        //Rename
        if (file.renameTo(newFile)) {
            System.out.println("File has been renamed.");
        } else {
            System.out.println("Error renmaing file");
        }
    }
}