Home » Java Codes

Java File I/O – How to rename a file (change file name)

13 February 2009 139 views No Comment

This code example shows how to change the name of a file.

import java.io.File;

/**
 *
 * @author www.javabout.com
 */

public class Main {

    public void renameFile(String file, String toFile) {

        File toBeRenamed = new File(file);

        if (!toBeRenamed.exists() || toBeRenamed.isDirectory()) {

            System.out.println(“File does not exist: “ + file);
            return;
        }

        File newFile = new File(toFile);

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

    }

    public static void main(String[] args) {
        new Main().renameFile(“C:\\temp\\file1.txt”, “C:\\temp\\file2.txt”);
    }
}


Tags: , , , , , , , , , , , , , ,

Leave your response!

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>