Utils { public static Path createFileWithUniqueName(final String baseName) throws IOException { if (baseName == null || baseName.isEmpty()) return null; String nameOnly = baseName; String ext = ""; final int startExt = baseName.lastIndexOf("."); if (startExt > 0) { nameOnly = baseName.substring(0, startExt); ext = baseName.substring(startExt); } Path targetPath = Paths.get(baseName); File f = null; int i = 1; while (f == null) { try { f = Files.createFile(targetPath).toFile(); } catch (final FileAlreadyExistsException faee) { targetPath = Paths.get(nameOnly + "-" + i++ + ext); } } return targetPath; }  static String toXMLDateTime(final Date date); static Date fromXMLDateTime(final String xmlDateTimeString); static String detectMimeType(final File f); static String getExtension(final String mimeType); static Path createFileWithUniqueName(final String baseName); static void sortFiles(final File array[]); static String getKeyByValue(final Map<String, String> map, final String value); static int compareStrings(final String s, final String p); static String getValue(final String value, final String defaultValue); static boolean isNullOrEmpty(final String s); static boolean isNullOrEmpty(final Collection<?> c); static boolean isNullOrEmpty(final Map<?,?> m); static boolean isNullOrEmpty(final Iterator<?> i); static Throwable getRootCause(final Throwable t); static List<Throwable> getCauses(final Throwable t); static String getExceptionTrace(final Throwable t); static boolean nullSafeEqual(final T o1, final T o2); static boolean nullSafeEqualIgnoreCase(final String s1, final String s2); static boolean isValidURI(final String uri); static boolean isTrue(String value);  }
@Test public void testPreventDuplicateFileName() { String baseDir = TestUtils.getPath("utils").toString(); try { File dir = new File(baseDir); assertTrue(dir.isDirectory()); File[] files = dir.listFiles(); if(files.length == 0) { new File(baseDir + "/emptyfile.xml").createNewFile(); new File(baseDir + "/emptyfile").createNewFile(); files = dir.listFiles(); } String newFileName1 = Utils.createFileWithUniqueName(baseDir + "/emptyfile.xml").toString(); String newFileName2 = Utils.createFileWithUniqueName(baseDir + "/emptyfile").toString(); assertNotEquals(newFileName1, newFileName2); for (File file : files) { assertNotEquals(file.getAbsolutePath(), newFileName1); assertNotEquals(file.getAbsolutePath(), newFileName2); } new File(newFileName1).delete(); new File(newFileName2).delete(); } catch (IOException e) { e.printStackTrace(); fail(); } }