Jan 222014
 
/* Copyright (c) 2014 Aaron Johnson
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
 * PARTICULAR PURPOSE.
 */

    /** Returns the next available non-existent file by incrementing a numerical value at the end of the file name. <br/> Copyright (c) 2014 Aaron Johnson <br/>
     * abcdefg.html -> abcdefg.1.html -> abcdefg.2.html -> abcdefg.3.html -> abcdefg.4.html <br/>
     * abcdefg -> abcdefg.1 -> abcdefg.2 -> abcdefg.3 -> abcdefg.4 <br/>
     * @param originalFile
     * @return
     */

    public static File findNextAvailableFilename(final File originalFile) {
        final Path originalPath = Paths.get(originalFile.getAbsolutePath());
        String extension = FilenameUtils.getExtension(originalPath.toString());

        // if there is no extension then we just add .
        if (extension.length() > 0) {
            extension = "." + extension;
            // if the number is in the extension then there is no extension - there is only the number.
            if (extension.matches("[.]\\d+")) {
                extension = "";
            }
        }
        Path path = originalPath;

        // loop until the file does not exist.
        while (Files.exists(path)) {
            // find and extract the number currently used.
            int number = 0;
            String newFilename = originalPath.getFileName().toString();
            if (newFilename.matches(".+[.]\\d+" + Pattern.quote(extension))) {
                number = Integer.valueOf(newFilename.replaceFirst(".+[.](\\d+)" + Pattern.quote(extension), "$1"));
            }
            number++;

            // if there is a number currently used then replace it.
            if (newFilename.matches(".+[.]\\d+" + Pattern.quote(extension))) {
                newFilename = newFilename.replaceFirst("(.+[.])(\\d+)" + Pattern.quote(extension), "$1" + number + extension);
            } else {
                // there is no number currently used so insert a number.
                final String filenameWithoutExtension = newFilename.substring(0, newFilename.length() - extension.length());
                newFilename = filenameWithoutExtension + "." + number + extension;
            }
            path = originalPath.getParent().resolve(newFilename);
        }

        return path.toFile();
    }


// -----------------------

    /** Copyright (c) 2014 Aaron Johnson <br/>
     * Test method for {@link #findNextAvailableFilename(java.io.File)}.
     * @throws IOException
     */

    @Test(timeout=3000)
    public void testFindNextAvailableFilenameWithExtension() throws IOException {
        final List<Path> filesToDelete = new LinkedList<>();
        try {
            final Path tempFolder = Paths.get(System.getProperty("java.io.tmpdir"));
            Path tempFile = tempFolder.resolve(FileDescriptionTestCase.class.getSimpleName() + ".html");

            // assure the file does not exist.
            Files.deleteIfExists(tempFile);

            // this should return the same name because the file name is available.
            File newFilename = FileUtils.findNextAvailableFilename(tempFile.toFile());
            assertEquals("The same file should have been returned because the file doesn't exist.",
                    newFilename.getAbsolutePath(), tempFile.toAbsolutePath().toString());

            // create the file.
            new FileOutputStream(tempFile.toFile()).close();
            filesToDelete.add(tempFile);
            assertTrue("The file should exist now. (This just assures that we have write access to the disk.)", Files.exists(tempFile));

            for (int i = 1; i < 100; i++) {
                newFilename = FileUtils.findNextAvailableFilename(tempFile.toFile());
                tempFile = Paths.get(newFilename.toString());
                assertFalse("File should not exist.", Files.exists(tempFile));
                assertEquals("The file was not named correctly.",
                        tempFile.getFileName().toString(), FileDescriptionTestCase.class.getSimpleName() + "." + i + ".html");

                new FileOutputStream(tempFile.toFile()).close();
                filesToDelete.add(tempFile);
                assertTrue("The file should exist now. (This just assures that we have write access to the disk.)", Files.exists(tempFile));
            }

        } finally {
            // delete all temp files
            for (final Path fileToDelete: filesToDelete) {
                try {
                    Files.deleteIfExists(fileToDelete);
                } catch (final Exception e) {
                    // ignored.
                }
            }
        }
    }

    /** Copyright (c) 2014 Aaron Johnson <br/>
     * Test method for {@link #findNextAvailableFilename(java.io.File)}.
     * @throws IOException
     */

    @Test//(timeout=3000)
    public void testFindNextAvailableFilenameWithoutExtension() throws IOException {
        final List<Path> filesToDelete = new LinkedList<>();
        try {
            final Path tempFolder = Paths.get(System.getProperty("java.io.tmpdir"));
            Path tempFile = tempFolder.resolve(FileDescriptionTestCase.class.getSimpleName());

            // assure the file does not exist.
            Files.deleteIfExists(tempFile);

            // this should return the same name because the file name is available.
            File newFilename = FileUtils.findNextAvailableFilename(tempFile.toFile());
            assertEquals("The same file should have been returned because the file doesn't exist.",
                    newFilename.getAbsolutePath(), tempFile.toAbsolutePath().toString());

            // create the file.
            new FileOutputStream(tempFile.toFile()).close();
            filesToDelete.add(tempFile);
            assertTrue("The file should exist now. (This just assures that we have write access to the disk.)", Files.exists(tempFile));

            for (int i = 1; i < 100; i++) {
                newFilename = FileUtils.findNextAvailableFilename(tempFile.toFile());
                tempFile = Paths.get(newFilename.toString());
                assertFalse("File should not exist.", Files.exists(tempFile));
                assertEquals("The file was not named correctly.",
                        tempFile.getFileName().toString(), FileDescriptionTestCase.class.getSimpleName() + "." + i);

                new FileOutputStream(tempFile.toFile()).close();
                filesToDelete.add(tempFile);
                assertTrue("The file should exist now. (This just assures that we have write access to the disk.)", Files.exists(tempFile));
            }

        } finally {
            // delete all temp files
            for (final Path fileToDelete: filesToDelete) {
                try {
                    Files.deleteIfExists(fileToDelete);
                } catch (final Exception e) {
                    // ignored.
                }
            }
        }
    }
 Posted by at 9:51 pm  Tagged with: