StackTips

How to Generate Unique File Name When Saving a File in Java

stacktips avtar

Written by

Editorial,  2 min read,  3.46K views, updated on Sept. 17, 2023

The following code snippet shows how to get a unique file name when saving the file in java. It first checks if already a file exists with the specified name, then it appends a number to the end.

public static File getUniqueFilePath(String parent, String child, String fileName) {
    File dir = new File(parent, child);
    String uniqueName = getUniqueFileName(parent, child, fileName);
    return new File(dir, uniqueName);
}

public static String getUniqueFileName(String parent, String child, String fileName) {
     final File dir = new File(parent, child);
     if (!dir.exists()) {
         dir.mkdirs();
     }

     int num = 0;
     final String ext = getFileExtension(fileName);
     final String name = getFileName(fileName);
     File file = new File(dir, fileName);
     while (file.exists()) {
         num++;
         file = new File(dir, name + "-" + num + ext);
     }
     return file.getName();
}

public static String getFileExtension(final String path) {
     if (path != null && path.lastIndexOf('.') != -1) {
         return path.substring(path.lastIndexOf('.'));
     }
     return null;
}


public static String getFileName(String fileName) {
     return fileName.substring(0, fileName.lastIndexOf('.'));
}

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!