0

[EDIT] I was not able to rename my file with renameTo() method of File class. Okay I searched and found a question explaining the same

File.renameTo() fails?

Also I read the Java Doc for renameTo() which says:

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

Okay, I understand that renameTo() method is platform-dependent.

Then I created the object of FileOutputStream and called close() method, now I tried renameTo() method and my file got renamed,

Question:

  • I was not able to understand the reason why after creating the object of FileOutputStream my renameTo() method worked?

Environment: Windows XP, User: Administrator

Code:

    File f = null;
    File f1 = null;
    boolean isFileRenamed = false;

    try {
        // create new File objects
        f = new File("C:\\originalFile.txt");
        f1 = new File("C:\\renamedFile.txt");

        // I need to write following code to rename the file
        // I tried without FileOutputStram object but then renameTo() did not work
        FileOutputStream fos = new FileOutputStream(f);
        fos.close();

        isFileRenamed = f.renameTo(f1);
        System.out.print("File renamed? " + isFileRenamed);

    } catch (Exception e) {
        e.printStackTrace();
    }

Searching for answer why renameTo() method worked after creating object of FileOutputStram. Also my application use Java1.6 so my option for Files class is closed. I will have to use renameTo() method only

Community
  • 1
  • 1
  • You're not just renaming the file but also want to make a copy of it into a new location. You have to split your logic into more tasks: 1. Open the file to copy with a `FileInputStream fis`. 2. Create a `FileOutputStream fos` with the new location and name of the file copy. 3. Read the contents from the `fis` and write them into `fos`. 4. Close the streams. – Luiggi Mendoza Jul 27 '13 at 17:23
  • 1
    Usually, like %99.999 of the time, it is NOT a bug in the langauge itself. – Jiminion Jul 27 '13 at 17:24
  • Does `C:\text.txt` exist before you're renaming it? Otherwise opening and closing the stream will create a new empty file. – millimoose Jul 27 '13 at 17:24
  • Maybe a stupid question, does the file `D:\\renamed.txt` already exist ? – bsd Jul 27 '13 at 17:25
  • @bsd `D:\\renamed.txt` probably doesn't exist. Why people don't read that original file is in C drive and the *renamed file* must be in D drive (which is odd, to begin with)? – Luiggi Mendoza Jul 27 '13 at 17:27
  • Also, if you're on Java SE 7, consider using [`Files.move()`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...)) which has not insane error reporting. – millimoose Jul 27 '13 at 17:27
  • @LuiggiMendoza whoa! okay, I thought I might ask. – bsd Jul 27 '13 at 17:29
  • @millimoose of course C:\text.txt exists then only i will be able to rename it :) –  Jul 27 '13 at 17:29
  • 1
    *"I can not say, but is this bug in java."* I'd lay 1000 to 1 odds that it is a bug in ***your*** code. For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Jul 27 '13 at 17:30
  • @joynee Well, as a "blow the dust out of the cartridge" move, can you check if running your code hasn't created a new empty .txt file under `C:\`? – millimoose Jul 27 '13 at 17:31
  • @millimoose it is not creating an empty file. –  Jul 27 '13 at 17:44
  • @joynee Please accept an answer to each of your questions if it satisfies your question. Use the checkmark next to an answer for that. This will mark the question as answered. – nanofarad Aug 02 '13 at 13:37
  • thanks @hexafraction for guiding me about StackOverFlow, appreciate, but still I am searching for the answer, just now I have edited for more clarity. –  May 03 '14 at 06:08
  • @bsd please revisit my question, might be earlier I was unclear. –  May 03 '14 at 06:11
  • @ruakh : I strongly don't feel that this question is duplicate, might be earlier I was unclear, that is why my question could have been miss-understood to be duplicate. Please revisit my question. –  May 03 '14 at 06:15

1 Answers1

5

It's not a bug in the JDK. From the documentation:

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

(My emphasis)

Different drives are different filesystems. Moving a file between file systems requires copying the file's data from the old filesystem to the new, and when the copy is complete, then deleting the file in its original location. renameTo doesn't take on that work, it's for the simple case where the file can simply be moved within the filesystem.


You say below that it doesn't even work within a file system. Note that if you're using Windows 7, you have to be running as Administrator to create files in the root of the C: drive.

This works if I run in a command prompt as Administrator:

Example code:

import java.io.*;

public class FileMove
{
    public static final void main(String[] args) {
        File f = null;
        File f1 = null;
        boolean bool = false;

        try {
            // create new File objects
            f = new File("C:\\test.txt");
            f1 = new File("C:\\renamed.txt");

            bool = f.renameTo(f1);

            System.out.print("File renamed? " + bool);

        } catch (Exception e) {
            // if any error occurs
            e.printStackTrace();
        }
    }
}

Example run:

C:\>echo "Testing 1 2 3">test.txt
C:\>type c:\test.txt
"Testing 1 2 3"
C:\>type c:\renamed.txt
The system cannot find the file specified.
C:\>java -cp . FileMove
File renamed? true
C:\>type renamed.txt
"Testing 1 2 3"
C:\>

But as millimoose points out in the comments, there's the Files.Move method.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • then why after making the obj of FileOutputStream i am able to rename my file name, please see my code. –  Jul 27 '13 at 17:27
  • @joynee: I don't believe your code (the code actually in the question) works (e.g., actually moves the file intact). All due respect, I believe you're mis-observing what's going on. To test: 1. Make sure `C:\test.txt` exists and is not blank. 2. Show the contents of `C:\test.txt`. 3. Run your code. 4. Show the contents of `D:\renamed.txt`. I believe you'll find that if `D:\renamed.txt` exists at all, it doesn't have the content that was originally in `C:\test.txt`. – T.J. Crowder Jul 27 '13 at 17:30
  • buddy even i am not able to rename in the same filesystem. –  Jul 27 '13 at 17:31
  • @joynee: I don't know what to tell you. `File#renameTo` works within a file system, so it must be how you're using it or (with apologies) observational error. – T.J. Crowder Jul 27 '13 at 17:34
  • @joynee So is there any particular reason why you still haven't tried `Files.move()` yet to see if it throws any exceptions that would tell us what's going on instead of just making everyone guess what "doesn't work" really means? – millimoose Jul 27 '13 at 17:34
  • @T.J. Crowder: test.txt exists, D:\renamed.txt does not exists, it will be created. Test.txt is not empty. but still not able to rename. –  Jul 27 '13 at 17:34
  • 1
    @millimoose i tried Files.move() but i wanted to use renameTo() to move my files. I wanted to find out why this method is not working if i am not using object of FileOutputStream. –  Jul 27 '13 at 17:39
  • kk thanks millimoose I will go with move(). but at the same time i will find out why this method is not working. –  Jul 27 '13 at 17:48
  • @joynee: Perhaps you're trying to write to a location where you have to have admin rights? (`C:\``, for instance). I've updated with code proving that `renameTo` **does** work within a file system. It won't work between file systems. But as millimoose points out, there's a better option. – T.J. Crowder Jul 27 '13 at 17:55
  • @T.J.Crowder I am having admin rights, but still their are issues with renameTo(), i don't know whether this is happening with me or not but i tried in other system also, i need to created object of FileOutputStream than only i am able to rename my file. Any way I am using Files.move() as suggested by millimoose, but I wanted to find out why i need to make an object of FileOutputStream to rename my file. –  Jul 28 '13 at 06:26
  • @joynee: It doesn't matter if you *have* admin rights, you have to have opened the command prompt "as administrator" (it won't do the usual pop-up). I'm sorry, but I don't believe that using a `FileOutputStream` changes anything (for the better; it could well get in the way). – T.J. Crowder Jul 28 '13 at 07:45
  • @T.J.Crowder even i agree with you, but the thing is when i am executing the above code, the file is not getting renamed without creating an obj of FileOutputStream and using its close(), thats why i got confused, that is the reason i am saying i will find out the reason why it is so. –  Jul 28 '13 at 10:31
  • @joynee: You'll have to provide a lot more detail about exactly what your environment is, exactly what you're trying when you're not doing it cross-file-system, exactly what you see, exactly what you type, the exact code you're using (because if you're still using what's in the question, of course that's going to fail). – T.J. Crowder Jul 28 '13 at 10:41