can file.renameTo replace a existing file?
// 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 destina开发者_Go百科tion?
}
If the file with name 'filename' already exists in the destination will it be replaced with a new one?
According to 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.
From 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 );
}
}
}
As it is system dependent you should not expect it to behave this or other way. Check it and implement your own logic.
精彩评论