java 只列出目录中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16391367/
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-10-31 22:50:31  来源:igfitidea点击:

Listing only files in directory

javafiledirectory

提问by user1669488

I have a folder with following structure

我有一个具有以下结构的文件夹

C:/rootDir/

rootDir has following files

test1.xml
test2.xml
test3.xml
testDirectory <------- This is a subdirectory inside rootDir

I'm only interested in the xml Files inside rootDir. Cuz If I use JDOM to read the XML the following code also considers the files inside "testDirectory" and spits out "content not allowed exception"

我只对 rootDir 中的 xml 文件感兴趣。因为如果我使用 JDOM 读取 XML,以下代码也会考虑“testDirectory”中的文件并吐出“内容不允许异常”

File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles();

how can I exclude the subdirectory while using listFiles method? Will the following code work?

如何在使用 listFiles 方法时排除子目录?下面的代码会起作用吗?

File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles(new FilenameFilter() {

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

回答by MadProgrammer

Use a FileFilterinstead, as it will give you access to the actual file, then include a check for File#isFile

使用 aFileFilter代替,因为它可以让您访问实际文件,然后检查File#isFile

File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        String name = pathname.getName().toLowerCase();
        return name.endsWith(".xml") && pathname.isFile();
    }
});

回答by hd1

Easier is to realise that the Fileobject has an isDirectorymethod, which would seem as if it were written to answer this very question:

更容易意识到File对象有一个isDirectory方法,它似乎是为了回答这个问题而编写的:

File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles();
for (File file : files) {
    if ( (file.isDirectory() == false) && (file.getAbsolutePath().endsWith(".xml") ) {
       // do what you want
    }
}

回答by Gangadhara Reddy S

File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles(new FilenameFilter()
 {

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

What is the problem with above code. You can use this for listing files by excluding subfolders.

上面的代码有什么问题。您可以通过排除子文件夹来使用它来列出文件。

FileFilter also do's same thing but it will be used when file name is not sufficent to listing the files. i.e if you want list all hidden files or readonly file etc. you can use FilteFilter

FileFilter 也做同样的事情,但它会在文件名不足以列出文件时使用。即如果你想列出所有隐藏文件或只读文件等,你可以使用 FilteFilter