3

我正在编写一种从文件夹和子文件夹中获取特定文件类型(例如 pdf 或 txt)的方法,但我缺乏解决此问题的方法。这是我的代码

  // .............list file
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();

    for (File file : fList) {
        if (file.isFile()) {
            System.out.println(file.getAbsolutePath());
        } else if (file.isDirectory()) {
            listf(file.getAbsolutePath());
        }
    }

我当前的方法列出所有文件,但我需要特定文件

4

6 回答 6

10

对于不需要通过子目录递归的过滤列表,您可以这样做:

directory.listFiles(new FilenameFilter() {
    boolean accept(File dir, String name) {
        return name.endsWith(".pdf");
    }});

为了提高效率,您可以提前创建 FilenameFilter 而不是每次调用。

在这种情况下,因为您也想扫描子文件夹,所以过滤文件没有意义,因为您仍然需要检查子文件夹。事实上,你已经快到了:

File directory = new File(directoryName);

// get all the files from a directory
File[] fList = directory.listFiles();

for (File file : fList) {
    if (file.isFile()) {
       if (file.getName().endsWith(".pdf")) {
           System.out.println(file.getAbsolutePath());
       }
    } else if (file.isDirectory()) {
        listf(file.getAbsolutePath());
    }
}
于 2013-12-05T13:49:58.877 回答
6
if(file.getName().endsWith(".pdf")) {
    //it is a .pdf file!
}

/ * ** /

于 2013-12-05T13:47:32.150 回答
2

尝试在函数 http://docs.oracle.com/javase/6/docs/api/java/io/FilenameFilter.html中使用 FilenameFilter 接口

http://www.mkyong.com/java/how-to-find-files-with-certain-extension-only/ - 对于具有扩展过滤器的代码

于 2013-12-05T13:51:56.233 回答
1

使用File.listFiles(FileFilter)

例子:

File[] fList = directory.listFiles(new FileFilter() {
    @Override
    public boolean accept(File file) {
        return file.getName().endSwith(".pdf");
    }
});
于 2013-12-05T13:51:09.477 回答
0

您可以使用 apache fileUtils 类

String[] exte= {"xml","properties"};
Collection<File> files = FileUtils.listFiles(new File("d:\\workspace"), exte, true);

for(File file: files){
     System.out.println(file.getAbsolutePath());
}
于 2013-12-05T13:56:03.433 回答
0

我的建议是使用FileUtilsNIO.2
NIO.2允许 Stream with Depth-First search,例如您可以在一行代码中打印所有具有指定扩展名的文件:

Path path = Path.get("/folder");
try{
    Files.walk(path).filter(n -> n.toString().endsWith(".extension")).forEach(System.out::println)
}catch(IOException e){
    //Manage exception
}
于 2017-04-20T12:08:09.567 回答