String (String fileName, Set<String> usedFileNames, @Nullable String preferredName) { String uniqueName; if (preferredName != null && !usedFileNames.contains(preferredName)) { uniqueName = preferredName; } else { uniqueName = fileName; if (usedFileNames.contains(uniqueName)) { int dotPos = uniqueName.lastIndexOf('.'); String name = dotPos < 0 ? uniqueName : uniqueName.substring(0, dotPos); String ext = dotPos < 0 ? "" : uniqueName.substring(dotPos); int i = 0; do { i++; uniqueName = name + i + ext; } while (usedFileNames.contains(uniqueName)); } } usedFileNames.add(uniqueName); return uniqueName; }