Java Rename File renameFileIfExists(File f)

Here you can find the source of renameFileIfExists(File f)

Description

* If the file f already exists, this method returns a new File object with a unique name formed by appending an integer.

License

Apache License

Parameter

Parameter Description
f A File

Return

A File with a name different from f's name, if f exists, else f.

Declaration

public static File renameFileIfExists(File f) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;

public class Main {
    /** *******************************************************************
     * If the file f already exists, this method returns a new File
     * object with a unique name formed by appending an integer.  If
     * the filename has a file type suffix, the integer is inserted
     * between the base name and the suffix.  If f does not exist, it
     * is simply returned.//from   w w w. j a va2  s .c  om
     *
     * @param f A File
     *
     * @return A File with a name different from f's name, if f
     * exists, else f.
     */
    public static File renameFileIfExists(File f) {

        File result = f;
        try {
            String canonicalPath = result.getCanonicalPath();
            int lidx = canonicalPath.lastIndexOf(".");
            String suff = "";
            String base = canonicalPath;
            if (lidx != -1) {
                suff = canonicalPath.substring(lidx);
                base = canonicalPath.substring(0, lidx);
            }
            int fc = 0;
            while (result.exists()) {
                fc++;
                result = new File(base + "-" + fc + suff);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}

Related

  1. renameFile(String source, String dest)
  2. renameFile(String sourcePath, String targetPath)
  3. renameFile(String src_pathname, String dest_pathname)
  4. renameFileFromChinese(File file)
  5. renameFileHard(File srcFile, File destFile)
  6. renameFileOnWindows(File oldFile, File newFile)
  7. renameFiles(File fileDirectory, String regex, String replacement)
  8. renameFiles(String rootDir, String sourcePostfix, String destPostfix)
  9. renameFolder(String destinationFolderPath, String zipFileName, String prefix)