Java File create a backup copy

Description

Java File create a backup copy


//package com.demo2s;
import java.io.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        File file = new File("Main.java");
        backup(file);/*from  www  .j ava2  s.c  o m*/
    }

    /**
     * Make a backup copy of the specified file, if the file exists. The backup file has the same name with a ".bak"
     * extension added. If there already exists a file with the same name and a ".bak" extension it will be deleted.
     * 
     * @param file The file to backup
     */
    public static void backup(File file) {
        if (file == null)
            throw new IllegalArgumentException("Null file in FileUtil.backup()");
        if (file.exists()) {
            File backup = new File(file.getAbsolutePath() + ".bak");
            if (backup.exists())
                backup.delete();
            file.renameTo(backup);
        }
    }
}



PreviousNext

Related