Java Rename File rename(File srcFile, String newName)

Here you can find the source of rename(File srcFile, String newName)

Description

rename.

License

Open Source License

Parameter

Parameter Description
srcFile an existing file to rename, must not be <code>null</code>
newName the new filename, must not be <code>null</code>

Exception

Parameter Description
NullPointerException if srcFile or newName is <code>null</code>
IOException if the newFile has exist

Declaration

public static void rename(File srcFile, String newName) throws IOException 

Method Source Code


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

import java.io.FileNotFoundException;

import java.io.IOException;

public class Main {
    /**/*from   w ww. j av a2s  . co  m*/
     * rename.
     * 
     * @param srcFile an existing file to rename, must not be <code>null</code>
     * 
     * @param newName the new filename, must not be <code>null</code>
     * 
     * @throws NullPointerException if srcFile or newName is <code>null</code>
     * 
     * @throws IOException if source is not exist or is directory
     * 
     * @throws IOException if the newFile has exist
     */
    public static void rename(File srcFile, String newName) throws IOException {
        if (srcFile == null) {
            throw new NullPointerException("Source must not be null");
        }
        if (newName == null || newName.length() == 0) {
            throw new NullPointerException("newName must not be null");
        }
        if (srcFile.exists() == false) {
            throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
        }
        if (srcFile.isDirectory()) {
            throw new IOException("Source '" + srcFile + "' exists but is a directory");
        }

        String parentPath = srcFile.getParentFile().getAbsolutePath();
        File newFile = new File(parentPath + File.separator + newName);
        if (newFile.exists()) {
            throw new IOException("Rename '" + srcFile + "' exists ,can not rename");
        }
        if (!srcFile.renameTo(newFile)) {
            throw new IOException("Can not rename from '" + srcFile + "' to '" + newFile + "'");
        }
    }
}

Related

  1. rename(File pFrom, File pTo, boolean pOverWrite)
  2. rename(File source, File dest)
  3. rename(File source, File target)
  4. rename(File src, File dest)
  5. rename(File src, String name)
  6. rename(final String src, final String dst)
  7. rename(String existingFile, String newFilename)
  8. rename(String fileName, String distFile)
  9. rename(String from, String to)