Java:将包含文件和目录的目录移动到新路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23346922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Move Directory containing files and directories to new path
提问by learner
I have one directory containing some files and sub directory having more files in it.
我有一个包含一些文件的目录和包含更多文件的子目录。
Folder - Directory (path -> /home/abc/xyz/Folder)
->Abc.txt (file)
-> Xyz.zip (file)
-> Address (Sub Directory)
-> PWZ.log (file)
-> CyZ.xml (file)
-> DataLog.7zip
etc
等等
What I am trying to do is move this complete Directory from one path to another including all the files and subfolder(and their files).
我想要做的是将这个完整的目录从一个路径移动到另一个路径,包括所有文件和子文件夹(及其文件)。
ie Move this "Folder" from /home/abc/xyz/Folder to /home/abc/subdir/Folder.
即将此“文件夹”从/home/abc/xyz/Folder 移动到/home/abc/subdir/Folder。
Does Java provides any API to do this task based on FOLDER directory or do we need to do recursive copy each and every file only to this path?
Java 是否提供任何 API 来根据 FOLDER 目录执行此任务,还是我们需要将每个文件递归复制到此路径?
采纳答案by flotothemoon
The best approach is probably a recursive method, like: This is a method I created for moving files into a temp folder.
最好的方法可能是递归方法,例如:这是我为将文件移动到临时文件夹而创建的方法。
private boolean move(File sourceFile, File destFile)
{
if (sourceFile.isDirectory())
{
for (File file : sourceFile.listFiles())
{
move(file, new File(file.getPath().substring("temp".length()+1)));
}
}
else
{
try {
Files.move(Paths.get(sourceFile.getPath()), Paths.get(destFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
return true;
} catch (IOException e) {
return false;
}
}
return false;
}
回答by Russell Zahniser
Files.move()
will work provided that the file system is able to "move" the file. This usually requires that you be moving to a different location on the same disk.
Files.move()
只要文件系统能够“移动”文件,就可以工作。这通常要求您移动到同一磁盘上的不同位置。
回答by Mani
You can simply move directory by using
您可以简单地使用移动目录
import static java.nio.file.StandardCopyOption.*;
Files.move(new File("C:\projects\test").toPath(), new File("C:\projects\dirTest").toPath(), StandardCopyOption.REPLACE_EXISTING);
Change source and destination path
更改源路径和目标路径
Refer hereto get more details
请参阅此处以获取更多详细信息
Also Note from API
来自 API 的注意事项
When invoked to move a
* directory that is not empty then the directory is moved if it does not
* require moving the entries in the directory. For example, renaming a
* directory on the same {@link FileStore} will usually not require moving
* the entries in the directory. When moving a directory requires that its
* entries be moved then this method fails (by throwing an {@code
* IOException}). To move a <i>file tree</i> may involve copying rather
* than moving directories and this can be done using the {@link
* #copy copy} method in conjunction with the {@link
* #walkFileTree Files.walkFileTree} utility method
If you try to move the file in the same partition , the above code is sufficient ( it can move directory even it has entries). if not ( instead of move) you need to use recursive as other answer mentioned.
如果您尝试移动同一分区中的文件,上面的代码就足够了(即使有条目,它也可以移动目录)。如果不是(而不是移动),您需要使用递归作为提到的其他答案。
回答by Doopy
If you have imported Apache Commonsalready anyways:
如果您已经导入了Apache Commons:
FileUtils.moveDirectory(oldDir, newDir);
Note that newDir
must not exist beforehand. From the javadocs:
请注意,newDir
必须事先不存在。从javadocs:
public static void moveDirectory(File srcDir, File destDir) throws IOException
Moves a directory. When the destination directory is on another file system, do a "copy and delete".
Parameters:
srcDir - the directory to be moved
destDir - the destination directoryThrows:
NullPointerException - if source or destination is null
FileExistsException - if the destination directory exists
IOException - if source or destination is invalid
IOException - if an IO error occurs moving the file
public static void moveDirectory(File srcDir, File destDir) throws IOException
移动目录。当目标目录在另一个文件系统上时,执行“复制和删除”。
参数:
srcDir - 要移动的目录
destDir - 目标目录抛出:
NullPointerException - 如果源或目标为 null
FileExistsException - 如果目标目录存在
IOException - 如果源或目标无效
IOException - 如果移动文件时发生 IO 错误
回答by AlikElzin-kilaka
Java has this built in, using native OS operation, in File.renameTo(File dest).
Java 在File.renameTo(File dest) 中使用本机操作系统操作内置了这个。
Example:
例子:
new File("/home/alik/Downloads/src").renameTo(new File("/home/alik/Downloads/target"))
回答by Louis CAD
You just need to use the renameTo
method (already present in the File
class from JDK) after you made sure the directories in the destination path are existing (e.g. by calling mkdirs()
).
在确保目标路径中的目录存在(例如通过调用)后,您只需要使用该renameTo
方法(已经存在于File
JDK的类中mkdirs()
)。
回答by user10262522
private static void move(File sourceFile, File destFile) {
if (sourceFile.isDirectory()) {
File[] files = sourceFile.listFiles();
assert files != null;
for (File file : files) move(file, new File(destFile, file.getName()));
if (!sourceFile.delete()) throw new RuntimeException();
} else {
if (!destFile.getParentFile().exists())
if (!destFile.getParentFile().mkdirs()) throw new RuntimeException();
if (!sourceFile.renameTo(destFile)) throw new RuntimeException();
}
}
works for me
为我工作