[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2111
  • Last Modified:

Problem with File.renameTo()

I am trying to move a file using renameTo() method. If a file with same name already exists it will not move the file. How to overcome it. I want to move the file even if it is existing already
0
sangameshrh
Asked:
sangameshrh
1 Solution
 
Ashish PatelCommented:
Try this method

    static String renameFile(
            final File source,
            final File target)
    {
        /* rename the specified file? */
        boolean renameFile = false;

        /* existing target file (to be overwritten), if any */
        File existingFile = null;
        String existingName = null;
        boolean existingIsDirectory = false;

        /* check if a distinct target file/directory already exists */
        if (target.exists() && !target.equals(source))
        {
            /* get attributes of the existing file/directory */
            try
            {
                existingFile = target.getCanonicalFile();
            }
            catch (Exception e)
            {
                existingFile = target;
            }

            existingIsDirectory = existingFile.isDirectory();
            existingName = trimTrailingSeparator(existingFile.getName()) +
                    (existingIsDirectory ? File.separatorChar : "");

            if (Sync.defaultActionOnOverwrite == 'Y')
            {
                SyncIO.printFlush("\n  Overwriting existing " +
                        (existingIsDirectory ? "directory" : "file") +
                        " \"" + existingName + "\"");
                renameFile = true;
            }
            else if (Sync.defaultActionOnOverwrite == 'N')
            {
                SyncIO.printFlush("\n  Skipping overwriting of existing " +
                        (existingIsDirectory ? "directory" : "file") +
                        " \"" + existingName + "\"");
            }
            else if (Sync.defaultActionOnOverwrite == '\0')
            {
                SyncIO.print("\n  Overwrite existing " +
                        (existingIsDirectory ? "directory" : "file") +
                        " \"" + existingName + "\"?\n");

                final char choice = SyncIO.userCharPrompt(
                        "  (Y)es/(N)o/(A)lways/Neve(R): ",
                        "YNAR");

                if (choice == 'Y')
                {
                    renameFile = true;
                }
                else if (choice == 'A')
                {
                    Sync.defaultActionOnOverwrite = 'Y';
                    renameFile = true;
                }
                else if (choice == 'R')
                {
                    Sync.defaultActionOnOverwrite = 'N';
                }
            }
        }
        else
        {
            /* target file does not exist, or is the same File as the source */
            renameFile = true;
        }

        if (renameFile)
        {
            /* delete existing file/directory first, if any */
            if (existingFile != null)
            {
                if (existingIsDirectory)
                {
                    final String error = deleteDirTreeOperation(existingFile);

                    if (error != null)
                        return "Failed to delete existing directory \"" +
                                trimTrailingSeparator(existingFile.getPath()) + File.separatorChar +
                                "\":\n" + error;
                }
                else
                {
                    final boolean success = existingFile.delete();

                    if (!success)
                        return "Failed to delete existing file \"" +
                                existingFile.getPath() + "\" using Java's File.delete() method.";
                }
            }

            /* rename file */
            final boolean success = source.renameTo(target);

            if (success)
            {
                return null; // success
            }
            else
            {
                return "Failed to rename file using Java's File.renameTo() method.";
            }
        }

        return ""; // aborted file rename
    }
0
 
Bart CremersJava ArchitectCommented:
Check if the new name exists before doing the renameTo:

    if (!newFile.exists() || newFile.delete()) {
        oldFile.renameTo(newFile);
    } else {
        System.out.println("No success");
    }

0
 
deeppraCommented:
check whether the file with the name exists if its there then delete the file and then try to rename it
0
 
zzynxSoftware engineerCommented:
I second the solution of Bart_Cr
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now