仅列出目录中的文件 [英] Listing only files in directory

查看:140
本文介绍了仅列出目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我只对rootDir中的xml文件感兴趣。 Cuz如果我使用JDOM读取XML,下面的代码也会考虑testDirectory中的文件并吐出内容不允许例外

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"

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

如何在使用listFiles方法时排除子目录?以下代码是否有效?

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

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


推荐答案

使用 FileFilter ,因为它可以让您访问实际文件,然后检查 文件#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();
    }
});

这篇关于仅列出目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆