Solved

Problem with File.renameTo()

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
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 learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

762 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now