如何在Java中将文件从一个位置移动到另一个位置? [英] How do I move a file from one location to another in Java?

查看:614
本文介绍了如何在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"));

文件#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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆