[英]How to rename a file using java.io packages?
如何使用java.io
包重命名文件?
File oldfile = new File(old_name);
File newfile = new File(new_name);
boolean Rename = oldfile.renameTo(newfile);
The boolean Rename
will be true if it successfully renamed the oldfile. 如果成功重命名旧文件,则布尔
Rename
将为true。
import java.io.File;
import java.io.IOException
public class Rename {
public static void main(String[] argv) throws IOException {
// Construct the file object. Does NOT create a file on disk!
File f = new File("Rename.java~"); // backup of this source file.
// Rename the backup file to "junk.dat"
// Renaming requires a File object for the target.
f.renameTo(new File("junk.dat"));
}
}
Reference: http://www.java2s.com/Code/Java/File-Input-Output/RenameafileinJava.htm 参考: http : //www.java2s.com/Code/Java/File-Input-Output/RenameafileinJava.htm
使用java.io.File
的renameTo
方法。
FWIW, as of Java 7 and later, the preferred answer for this should probably be to use java.nio.file.Files#move
: FWIW,从Java 7及更高版本开始,对此的首选答案应该是使用
java.nio.file.Files#move
:
java.nio.file.Files.move(oldPath, newPath, StandardCopyOption.ATOMIC_MOVE)
The reason why one would prefer this approach is because of this documented behavior in java.io.File#renameTo
: 人们更喜欢这种方法的原因是因为
java.io.File#renameTo
中这种记录的行为java.io.File#renameTo
:
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.
应始终检查返回值以确保重命名操作成功。
Note that the Files class defines the move method to move or rename a file in a platform independent manner.
请注意,Files类定义了以独立于平台的方式移动或重命名文件的移动方法。
When using java.nio.file.Files#move
, one can specify standard CopyOption
parameters that indicate more nuanced behavior (eg, what you want to happen if the file already exists, whether it must be done atomically, etc.) 当使用
java.nio.file.Files#move
,可以指定标准的CopyOption
参数来指示更细微的行为(例如,如果文件已经存在,您是否希望发生什么,是否必须以原子方式完成等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.