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

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

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('.'));
}
Total
0
Shares
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ajoy Bhatia
Ajoy Bhatia
3 years ago

So, all that getUniqueFileName is doing is appending an integer to the filename. However it is not very efficient if a large number of files are going to be created and are not deleted. On every call, it starts counting from 0 to look for the next number that creates a unique filename. So, after 1000 files have been created, the next call will again start the while loop counting from 0 incrementing by 1 to reach 1001 that will finally give a unique file name.

Previous Post

How to Calculate Image Dimensions in Java

Next Post

How to Generate Gravtar Image Url from Email in Java

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
1
0
Would love your thoughts, please comment.x
()
x