Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Problem with File.renameTo()

Posted on 2007-11-14
6
Medium Priority
?
2,099 Views
Last Modified: 2008-09-20
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
Comment
Question by:sangameshrh
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 23

Expert Comment

by:Ashish Patel
ID: 20287413
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
 
LVL 13

Accepted Solution

by:
Bart Cremers earned 2000 total points
ID: 20287418
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
 
LVL 5

Expert Comment

by:deeppra
ID: 20287482
check whether the file with the name exists if its there then delete the file and then try to rename it
0
 
LVL 37

Expert Comment

by:zzynx
ID: 20287518
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.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
This video teaches viewers about errors in exception handling.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

609 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question