Solved

Problem with File.renameTo()

Posted on 2007-11-14
6
2,066 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
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 500 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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

809 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