java renameto false,java file.renameTo()重命名文件,但返回false。为什么?

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 file in windows explorer it has a new name and it moved.

Just curious why this is happening.

here is some sample code I just tried to recreate the issue. It's pretty much the same thing and it's working fine.

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: Solved it. I'm sorry for wasting everyone's time with something so silly. However, I really dont think I would have tracked this down if not for making this post.

The solution was that I was actually looping through several files to move. When the output said it failed then the program stopped and when I looked in explorer only the first of the files was actually moved so I assumed it was moving and then returning false. However, the issue was that I was using the wrong variable as an index and so what was happeneing was that it did successfully move the file in index 0 and then when the loop repeated the index didnt increment so it tried to move index 0 again and therefore failed.

Like I said, very stupid but thanks for bearing with me.

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值