我一直在讨论与FilenameFilter相关的问题。我想将我的类的实现FilenameFilter的对象传递给一个方法,该方法以递归方式将文件传递到文件夹树中。没有作为参数传递的FilenameFilter对象的此方法的一个版本工作正常,但是重载版本没有。问题是它不会递归地进入文件夹树,尽管它应该。也许一个可能的问题与 accept(File dir,String name)的参数有关; 方法,有两个参数,我不太确定我是否以及如何将值传递给他们......我将非常感谢任何帮助...... PS。 方法 listfilesRecursive(FilenameFilter filter)使用一个参数处理类 MyFile 的对象,因此一个字段路径
public class MyFile {
String path;
public MyFile (String path) {
this.path = path;
}
List <File> list = new ArrayList<File> ();
List <String> nameList = new ArrayList <String> ();
public List <File> listFilesRecursive(FilenameFilter fFilter) {
File f1 = new File(path);
File [] files = f1.listFiles(fFilter);
for (File fil : files) {
if (fil.isFile()) {
list.add(fil);
nameList.add(fil.getName());
} else if (fil.isDirectory()) {
this.path = fil.toString();
this.listFilesRecursive(fFilter);
}
}
Collections.sort(nameList);
return list;
}
以下是实现FilenameFilter的类:
class MyFilenameFilter implements FilenameFilter {
String ext;
public MyFilenameFilter (String ext) {
this.ext = ext;
}
@Override
public boolean accept(File dir, String name) {
// System.out.println(name + " <<<<<<<<<<");
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(ext))
{
return true;
}
}
return false;
}
}
最后,FilenameFilter是一个不错的选择,如果我想实现一个方法,通过文件夹选择它们并根据它们的名称对它们进行过滤?
答案 0 :(得分:0)
package hasses.magical.xml.formatter;
import static hasses.magical.xml.formatter.UIOut.uiOut;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FormattingController
{
private FilenameFilter fileFilter;
public FormattingController(FormatParam settings)
{
super();
this.settings = settings;
//File filter can of course be any old FileNameFilter implementation
fileFilter = new MagicFileNameFilter(settings);
}
private FormatParam settings;
public Integer excecute()
{
//In this case dir is set from a placeholder but any old string will do
try (Stream<Path> walk = Files.walk(Paths.get(settings.getDir()))) {
//forEach can ofcourse be called path->formatFile(path, someOtherCoolParam) if needed
walk.filter(path->fileFilter.accept(null, path.toFile().getName())).forEach(this::formatFile);
} catch (IOException e) {
uiOut("IOException during traverse dir: %s please check this a valid directory",settings.getDir());
return -99;
}
return 0;
}
private void formatFile(Path path)
{
if(settings.getVerbose()) {
uiOut("Will attempt to format: %s",path);
}
//do formatting or whatever...
}
}