Java – Check if File Exists and Generate a Unique Name

Java – Check if File Exists and Generate a Unique Name

0 5066

folder-with-file-icon-hi
Today I wanted to share a utility I whipped up. I wanted the utility to accept a File Object and be able to do the following:

  • Check if the file name exists, if it does NOT, return the File passed in.
  • Generate a random number between 1000 and 9999 and insert it before the file extension, or at the end of the name if there is no extension.
  • Repeat the process if necessary until we find a unique name.

Here is the class below free of any third party dependencies. You have my permission to use it however you see fit.

public class FileUtils {

    private static Random random = new Random();

    /**
     * 
     * @param f
     * @return
     *      A unique file name or the file passed in if it does not exist
     */
    public static File getUniqueFile(File f) {
        if(!f.exists()) {
            return f;
        }

        StringBuilder fsb = new StringBuilder(f.getName());
        int insertion = fsb.lastIndexOf(".");
        if (insertion == -1) {
            insertion = fsb.length();
        }


        int rand = randInt(1000, 9999);
        fsb.insert(insertion, rand);
        File randFile = new File(f.getParentFile(), fsb.toString());
        if(randFile.exists()) {
            //keep going until we get something unique
            return getUniqueFile(f);
        }

        return randFile;
    }


    public static int randInt(int min, int max) {
        return random.nextInt((max - min) + 1) + min;

    }

}

NO COMMENTS

Leave a Reply