java file.renameTo() does rename file but returns false. Why?

前端 未结 3 877
-上瘾入骨i
-上瘾入骨i 2021-01-02 18:23

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 on the fil

相关标签:
3条回答
  • 2021-01-02 18:49

    This one 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 a file myDoc.txt and rename it to new.txt and will print true
    I've also tried with File(URI) constructor it worked fine

    0 讨论(0)
  • 2021-01-02 18:51

    Java's File.renameTo() is problematic, especially on Windows, it seems. As the API documentation 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.

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

    0 讨论(0)
  • 2021-01-02 18:56

    Isn't it possible that you file has a Inputstream open somewhere but has not been closed and so the rename is not working. Try closing all open streams relevant to the file object before closing.

    0 讨论(0)
提交回复
热议问题