如何在 Java 中将文件从一个位置移动到另一个位置? [英] How do I move a file from one location to another in Java?
问题描述
如何将文件从一个位置移动到另一个位置?当我运行我的程序时,在该位置创建的任何文件都会自动移动到指定位置.我怎么知道哪个文件被移动了?
How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?
推荐答案
myFile.renameTo(new File("/the/new/place/newName.file"));
File#renameTo 就是这样做的(它不仅可以重命名,还可以在目录之间移动,至少在同一个文件系统上).
File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).
重命名由这个抽象路径名表示的文件.
Renames the file denoted by this abstract pathname.
此方法行为的许多方面本质上是平台相关的:重命名操作可能无法将文件从一个文件系统移动到另一个文件系统,它可能不是原子的,并且如果文件带有目标抽象路径名已存在.应始终检查返回值以确保重命名操作成功.
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.
如果您需要更全面的解决方案(例如想要在磁盘之间移动文件),请查看 Apache Commons FileUtils#moveFile
If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile
这篇关于如何在 Java 中将文件从一个位置移动到另一个位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!