Here you can find the source of renameFileIfExists(File f)
Parameter | Description |
---|---|
f | A File |
public static File renameFileIfExists(File f)
//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; } }