Here you can find the source of renameFile(File srcFile, File destFile)
public static boolean renameFile(File srcFile, File destFile)
//package com.java2s; /*####################################################### * * Maintained by Gregor Santner, 2017- * https://gsantner.net//*from w w w .j a va 2s .c om*/ * * License: Apache 2.0 * https://github.com/gsantner/opoc/#licensing * https://www.apache.org/licenses/LICENSE-2.0 * #########################################################*/ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import java.util.UUID; public class Main { private static final int BUFFER_SIZE = 4096; public static boolean renameFile(File srcFile, File destFile) { if (srcFile.getAbsolutePath().equals(destFile.getAbsolutePath())) { return false; } // renameTo will fail in case of case-changed filename in same dir.Even on case-sensitive FS!!! if (srcFile.getParent().equals(destFile.getParent()) && srcFile.getName().toLowerCase(Locale.getDefault()) .equals(destFile.getName().toLowerCase(Locale.getDefault()))) { File tmpFile = new File(destFile.getParent(), UUID.randomUUID().getLeastSignificantBits() + ".tmp"); if (!tmpFile.exists()) { renameFile(srcFile, tmpFile); srcFile = tmpFile; } } if (!srcFile.renameTo(destFile)) { if (copyFile(srcFile, destFile) && !srcFile.delete()) { if (!destFile.delete()) { return false; } return false; } } return true; } public static boolean copyFile(final File src, final File dst) { // Just touch file if src is empty if (src.length() == 0) { return touch(dst); } InputStream is = null; FileOutputStream os = null; try { try { is = new FileInputStream(src); os = new FileOutputStream(dst); byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } return true; } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } } catch (IOException ex) { return false; } } public static boolean touch(File file) { try { if (!file.exists()) { new FileOutputStream(file).close(); } return file.setLastModified(System.currentTimeMillis()); } catch (IOException e) { return false; } } }