简体   繁体   English

从文件夹及其子文件夹中查找特定文件类型

[英]find specific file type from folder and its sub folder

I am writing a method to get specific file type such as pdf or txt from folders and subfolders but I am lacking to solve this problem. 我正在编写一个方法来从文件夹和子文件夹中获取特定文件类型,如pdf或txt,但我不能解决这个问题。 here is my code 这是我的代码

  // .............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());
        }
    }

My current method list all files but I need specific files 我当前的方法列出所有文件,但我需要特定的文件

For a filtered list without needing recursion through sub directories you can just do: 对于不需要通过子目录递归的筛选列表,您可以这样做:

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

For efficiency you could create the FilenameFilter ahead of time rather than for each call. 为了提高效率,您可以提前创建FilenameFilter而不是每次调用。

In this case because you want to scan sub folders too there is no point filtering the files as you still need to check for sub folders. 在这种情况下,因为您还要扫描子文件夹,所以无需过滤文件,因为您仍需要检查子文件夹。 In fact you were very nearly there: 事实上你几乎就在那里:

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());
    }
}
if(file.getName().endsWith(".pdf")) {
    //it is a .pdf file!
}

/ * ** / / * ** /

Use File.listFiles(FileFilter) . 使用File.listFiles(FileFilter)

Example: 例:

File[] fList = directory.listFiles(new FileFilter() {
    @Override
    public boolean accept(File file) {
        return file.getName().endSwith(".pdf");
    }
});

You can use apache fileUtils class 您可以使用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());
}

My advice is to use FileUtils or NIO.2 . 我的建议是使用FileUtilsNIO.2
NIO.2 allows Stream with Depth-First search, for example you can print all files with a specified extension in one line of code: NIO.2允许Stream使用Depth-First搜索,例如,您可以在一行代码中打印具有指定扩展名的所有文件:

Path path = Path.get("/folder");
try{
    Files.walk(path).filter(n -> n.toString().endsWith(".extension")).forEach(System.out::println)
}catch(IOException e){
    //Manage exception
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM