Java Rename File rename(File from, File to)

Here you can find the source of rename(File from, File to)

Description

rename file

License

Open Source License

Parameter

Parameter Description
from a parameter
to a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void rename(File from, File to) throws IOException 

Method Source Code


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

public class Main {
    /**//  w w  w . java2s .c  om
     * rename file 
     *
     * @param from
     * @param to
     * @throws IOException
     */
    public static void rename(File from, File to) throws IOException {
        if (to.exists() && !to.delete()) {
            throw new IOException("Failed to delete " + to + " while trying to rename " + from);
        }
        File parent = to.getParentFile();
        if (parent != null && !parent.exists() && !parent.mkdirs()) {
            throw new IOException("Failed to create directory " + parent + " while trying to rename " + from);
        }
        if (!from.renameTo(to)) {
            copyFile(from, to);
            if (!from.delete()) {
                throw new IOException("Failed to delete " + from + " while trying to rename it.");
            }
        }
    }

    /**
     * file delete method
     *
     * @param file
     */
    public static void delete(File file) {
        if (file != null) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

    public static void copyFile(File source, File target) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(source));
            out = new BufferedOutputStream(new FileOutputStream(target));
            int ch;
            while ((ch = in.read()) != -1) {
                out.write(ch);
            }
            out.flush(); // just in case
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException ioe) {
                }
            if (in != null)
                try {
                    in.close();
                } catch (IOException ioe) {
                }
        }
    }
}

Related

  1. rename(File f1, File f2)
  2. rename(File file, String newName, boolean overwite)
  3. rename(File file, String prefix, String name, HashMap optional)
  4. rename(File from)
  5. rename(File from, File to)
  6. rename(File from, File to)
  7. rename(File from, File to)
  8. rename(File from, File to)
  9. rename(File from, File to)