find specific file type from folder and its sub folder

笑着哭i 提交于 2019-12-10 20:34:16

问题


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. 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


回答1:


if(file.getName().endsWith(".pdf")) {
    //it is a .pdf file!
}

/***/




回答2:


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.

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



回答3:


Try using the FilenameFilter interface in you function http://docs.oracle.com/javase/6/docs/api/java/io/FilenameFilter.html

http://www.mkyong.com/java/how-to-find-files-with-certain-extension-only/ - for a code that has extention filter




回答4:


Use File.listFiles(FileFilter).

Example:

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



回答5:


You can use apache fileUtils class

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

for(File file: files){
     System.out.println(file.getAbsolutePath());
}



回答6:


My advice is to use FileUtils or NIO.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:

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


来源:https://stackoverflow.com/questions/20401610/find-specific-file-type-from-folder-and-its-sub-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!