【发布时间】:2023-04-06 02:03:01
【问题描述】:
我正在处理学校作业,我们正在做简单的文件管理器,它应该将所有后缀为 "jpg"(例如)的文件移动到另一个文件夹中。问题是我们应该递归地遍历所有文件夹。
示例:您位于“下载”文件夹中:
--downloads
----me.jpg
----smth.doc
----folder1
------you.jpg
现在您必须将所有 .jpg 文件移动到文件夹“photos”并在那里创建“folder1”并移动文件“you.jpg”
这是我所拥有的,但它似乎只从“下载文件夹”中移动文件
private void move(String suffix, String sourcePath, String destination) throws IOException{
File dir = new File(sourcePath);
File destDir = new File(destination);
String src;
String dst;
for (File f : dir.listFiles(new ExtensionFilter(suffix))){
String name = f.getName();
src = f.getAbsolutePath();
dst = destination + "\\" + name;
Files.createDirectories(Paths.get(destination));
Files.move(Paths.get(src), Paths.get(dst));
logs.add("MV;" + src + ";" + dst);
}
for (File f : dir.listFiles(new DirectoryFilter())){
move(suffix, f.getPath(), destination + "\\" + f.getName());
}
}
logs 就是 ArrayList 用来保存记录哪些文件被移动了
【问题讨论】:
-
首先查看Walking the File Tree 和Finding Files,或者,如果您不允许使用这些方法,您也可以查看使用
File的this example API
标签: java io filesystems