Java File Rename renameFile(File srcFile, File renameToFile)

Here you can find the source of renameFile(File srcFile, File renameToFile)

Description

rename File

License

Open Source License

Declaration

public static boolean renameFile(File srcFile, File renameToFile) throws IOException 

Method Source Code

//package com.java2s;
/*//from w  w w  . jav  a  2 s . c  om
 * Copyright (c) 2002-2015 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

public class Main {
    private static final int WINDOWS_RETRY_COUNT = 5;

    public static boolean renameFile(File srcFile, File renameToFile) throws IOException {
        if (!srcFile.exists()) {
            throw new FileNotFoundException("Source file[" + srcFile.getName() + "] not found");
        }
        if (renameToFile.exists()) {
            throw new FileNotFoundException("Target file[" + renameToFile.getName() + "] already exists");
        }
        if (!renameToFile.getParentFile().isDirectory()) {
            throw new FileNotFoundException("Target directory[" + renameToFile.getParent() + "] does not exists");
        }
        int count = 0;
        boolean renamed;
        do {
            renamed = srcFile.renameTo(renameToFile);
            if (!renamed) {
                count++;
                waitAndThenTriggerGC();
            }
        } while (!renamed && count <= WINDOWS_RETRY_COUNT);
        return renamed;
    }

    private static void waitAndThenTriggerGC() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException ee) {
            Thread.interrupted();
        } // ok
        System.gc();
    }
}

Related

  1. renameFile(File src, File dest)
  2. renameFile(File src, File dest)
  3. renameFile(File src, File dest, boolean overwrite)
  4. renameFile(File srcFile, File destFile)
  5. renameFile(File srcFile, File dstFile)
  6. renameFile(final File path, final String fname)
  7. renameFile(final String oldName, final String newName)
  8. renameFile(String currentPath, String newPath)
  9. renameFile(String file, String toFile)