使用 JAVA 从目录中检索所有 XML 文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20565333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:51:21  来源:igfitidea点击:

Retrieve all XML file names from a directory using JAVA

javadirectoryjava-io

提问by user3089869

I have a directory with multiple files. I need to retrieve only XML file names in a List using Java. How can I accomplish this?

我有一个包含多个文件的目录。我只需要使用 Java 检索列表中的 XML 文件名。我怎样才能做到这一点?

采纳答案by BlackPOP

Try this, {FilePath} is directory path:

试试这个,{FilePath} 是目录路径:

public static void main(String[] args) {
    File folder = new File("{FilePath}");
    File[] listOfFiles = folder.listFiles();
    for(int i = 0; i < listOfFiles.length; i++){
        String filename = listOfFiles[i].getName();
        if(filename.endsWith(".xml")||filename.endsWith(".XML")) {
            System.out.println(filename);
        }
    }
}

回答by Stephan

You can use also a FilenameFilter:

您还可以使用 FilenameFilter:

import java.io.File;
import java.io.FilenameFilter;

public class FileDemo implements FilenameFilter {
    String str;

    // constructor takes string argument
    public FileDemo(String ext) {
        str = "." + ext;
    }

    // main method
    public static void main(String[] args) {

        File f = null;
        String[] paths;

        try {
            // create new file
            f = new File("c:/test");

            // create new filter
            FilenameFilter filter = new FileDemo("xml");

            // array of files and directory
            paths = f.list(filter);

            // for each name in the path array
            for (String path : paths) {
                // prints filename and directory name
                System.out.println(path);
            }
        } catch (Exception e) {
            // if any error occurs
            e.printStackTrace();
        }
    }

    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(str.toLowerCase());
    }
}

回答by Dragon

You can filter by using File.filter(FileNameFilter). Provide your implementation for FileNameFilter

您可以使用 File.filter(FileNameFilter) 进行过滤。提供您对 FileNameFilter 的实现

回答by user3548196

File f = new File("C:\");
if (f.isDirectory()){
   FilenameFilter filter =  new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if(name.endsWith(".xml")){
                    return true;
                }
                return false;
            }
        };
   if (f.list(filter).length > 0){
      /* Do Something */
   }
}