如何使用Java代码将文件夹(包括子目录和文件)移动到新文件夹中
任何人都可以帮我编写一个 Java 代码,将一个文件夹复制或移动到另一个文件夹中。
例如:
我有一个名为 temp
的文件夹,在 temp
内有一个文件夹 in-temp
。
我希望将我的 temp
文件夹复制或移动到名为 new temp
的新文件夹中,但使用 Java 代码。
我通过在 Google 上搜索得到了一个示例代码,它将文件夹的子目录和文件复制到新文件夹中,但正如我所说,我需要使用以下命令移动文件夹它的子文件夹到一个新文件夹中。
帮我解决这个问题。
谢谢。
Can anyone help me for a Java code which copy or move one folder as it is into another folder.
For example:
I have a folder named temp
, inside temp
I have a folder in-temp
.
I want that my temp
folder should be copied or moved into a new folder named new temp
, but by using Java code.
I got an example code by searching on Google which copies the sub-directories and files of a folder into a new folder, but as I said I need to move a folder with it's sub-folder into a new folder.
Help me to resolve this.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 apache-commons-io:
You can use apache-commons-io:
对于大多数情况,特别是当源和目标位于同一文件系统(分别为驱动器)时,标准 java.nio
Files.move(路径源、路径目标、CopyOption...选项)
命令(自 Java 7 起可用)正是您所需要的。但是,该命令在某些情况下将失败,因此您必须诉诸/后备来复制和复制。递归删除目录(这种模式也可以在 commons-io 的FileUtils.moveDirectory
)。这是我最近在 Spring Boot 项目中实现的一个辅助方法(作为使用本机和现有 spring 方法从项目堆栈中删除 commons-io 的努力的一部分):
两个 FileSystemUtils方法是 spring 框架的一部分,但是如果您没有基于 spring 的项目......它们的实现非常简单:)
我在下面记录它们,以下只是原始 源代码来自 Github。
这段代码效果很好 - 如果您不确定自己在看什么,那么您需要对 文件访问者 API – 这是一种非常强大的模式,可以出于多种目的有效地遍历目录(即获取文件夹大小、列出文件等)。
For most cases, specifically when source and target are on the same filesystem, respectively drive, the standard java.nio
Files.move(Path source, Path target, CopyOption... options)
command (available since Java 7) does exactly what you need. However, the command will fail in some cases, so you'd have to resort/fallback to to copy & delete the directory recursively (this pattern is also found in commons-io'sFileUtils.moveDirectory
).This is a helper method that i just recently implemented in a Spring Boot project (as part of an effort to remove commons-io from the project's stack, using native & existing spring methods):
The two
FileSystemUtils
methods are part of the spring framework, but if you don't have a spring-based project… their implementations are pretty straightforward :)I am documenting them here below, the following is just a copy from the original source code from Github.
This code works great – if you're not sure what you're looking at here, then you'll want to develop a basic understanding of the File Visitor API – which is a really powerful pattern to efficiently traverse directories for a multitude of purposes (i.e. get folder size, list files, etc.).