java 可以用file.rename 来替换现有文件吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6569008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:24:32  来源:igfitidea点击:

can file.renameTo replace a existing file?

javafilefile-io

提问by akshay

// File (or directory) to be moved
File file = new File("filename");

// Destination directory
File dir = new File("directoryname");

// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
    // File was not successfully moved
    //can it be because file with file name already exists in destination?
}

If the file with name 'filename' already exists in the destination will it be replaced with a new one?

如果目标文件中已经存在名为“filename”的文件,它会被一个新文件替换吗?

采纳答案by mnicky

According to Javadoc:

根据Javadoc

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.

此方法行为的许多方面本质上是平台相关的:重命名操作可能无法将文件从一个文件系统移动到另一个文件系统,它可能不是原子的,并且如果具有目标抽象路径名的文件可能不会成功已经存在。应始终检查返回值以确保重命名操作成功。

回答by stacker

From Javadoc:

来自 Javadoc:

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.

重命名操作可能无法将文件从一个文件系统移动到另一个文件系统,它可能不是原子的,并且如果具有目标抽象路径名的文件已经存在,它可能不会成功。

I tested the following code:

我测试了以下代码:

It works the first time, second time it fails as expected. To move a file you should delete or rename the destination if required.

它第一次工作,第二次它按预期失败。要移动文件,您应该根据需要删除或重命名目标。

public class Test {
    public static void main(String[] args) throws IOException {
        File file = new File( "c:\filename" );
        file.createNewFile();
        File dir = new File( "c:\temp" );
        boolean success = file.renameTo( new File( dir, file.getName() ) );
        if ( !success ) {
            System.err.println( "succ:" + success );
        }
    }
}

回答by Rostislav Matl

As it is system dependent you should not expectit to behave this or other way. Check it and implement your own logic.

由于它依赖于系统,因此您不应期望它以这种或其他方式行事。检查它并实现你自己的逻辑。