Java file.renameTo () renames the file, but returns false. What for?

The problem is that I need the file to move before the rest of my logic will work, so when the method returns false, I stop execution.

However, when I check the file in Windows Explorer, it has a new name and it moves.

Just curious why this is happening.

here is an example of the code that i was just trying to recreate. This is pretty much the same, and it works great.

File testfile = new File("TestFile"); if(!testfile.exists()){ testfile.mkdirs(); } File sample = new File("sample.txt"); if(sample.exists()){ boolean success = sample.renameTo(new File(testfile.getPath() + "\\" + sample.getName())); if(success){ System.out.println("Moved"); } else{ System.out.println("Failed"); } } 

Edit: Decided. I apologize for spending all the time on something so stupid. However, I really do not think that I would have tracked this, if not for this.

The solution was that I actually iterated over several files to move. When the output indicated that this did not succeed, the program stopped, and when I looked in the explorer, only the first of the files was really moved, so I assumed that it moves, and then returns false. However, the problem was that I used the wrong variable as an index, and therefore it happened that it successfully moved the file to index 0, and then when the loop repeats, the index did not increase, so it tried to move index 0 again and therefore not managed.

As I said, itโ€™s very stupid, but thank you for being with me.

+4
source share
3 answers

Java File.renameTo() is problematic, especially on Windows, it seems. As stated in the API documentation:

Many aspects of the behavior of this method are inherently platform-dependent: the renaming operation may not be a file from one file system to another, it may not be atomic, or it may not work if a file with the target destination name already exists. You always need to check the return value to make sure that the rename operation is successful.

You can use the apache.commons.io library, which includes FileUtils.moveFile() or also the Files.move() method in JDK 7.

+9
source

Is it possible that your file has an input stream that opens somewhere, but was not closed, and therefore renaming does not work. Try closing all open threads related to the file object before closing.

0
source

It worked for me

 File file = new File("E:/Javadocs/" , "new.txt"); File file1 = new File("E:/Javadocs/" , "myDoc.txt"); file1.createNewFile(); if (file1.exists()){ System.out.println(file1.renameTo(file)); } 

This will create the myDoc.txt file and rename it to new.txt and display true | I also tried using a file constructor (URI) that worked fine

0
source

All Articles