The following code snippet shows how to get unique file name when saving file in java. It first checks if already a file exist with the specified name, then it appends a number to 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('.'));
}
Tagged in : #Java

Nilanchala

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3), DZone MVB and founder of stacktips.com.

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.