Java:将包含文件和目录的目录移动到新路径 [英] Java: Move Directory containing files and directories to new path
问题描述
文件夹 - 目录(路径 - > ; / home / abc / xyz / Folder)
- > Abc.txt(文件)
- > Xyz.zip(文件)
- >地址(子目录)
- > PWZ.log(文件)
- > CyZ.xml(文件)
- > DataLog.7zip
etc
我试图做的是将这个完整的目录从一个路径移动到另一个包括所有的文件和子文件夹(及其文件)。
$ b
即将这个文件夹从/ home / abc / xyz /文件夹到/ home / abc / subdir /文件夹。
Java是否提供了基于FOLDER目录的API来完成这项任务,还是我们需要做的递归复制每个文件只有这个路径?最好的方法可能是一个递归的方法,如:
这是我为移动文件创建的方法(文件源文件,文件目录文件)
{
if(sourceFile .isDirectory())
{
for(File file:sourceFile.listFiles())
{
move(file,new File(file.getPath()。substring(温度。长度()+ 1)));
{
try {
Files.move(Paths.get(sourceFile.getPath()),Paths.get(destFile .getPath()),StandardCopyOption.REPLACE_EXISTING);
返回true;
} catch(IOException e){
return false;
}
}
return false;
}
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.
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?
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;
}
这篇关于Java:将包含文件和目录的目录移动到新路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!