How to rename a file (change file name)

import java.io.File;

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");
    }
}

0 comments:

                                                                

Site Meter