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

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

问题描述

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

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文件感兴趣,因为如果我用JDOM读取XML,下面的代码也会考虑testDirectory里面的文件,吐出content not allowed 异常

I'm only interested in the XML files inside rootDir because 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 the 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 代替,因为它会让您访问实际文件,然后检查 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();
    }
});

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

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