File操作 - list()/listFiles()与目录过滤器

本文详细介绍了Java中File类的list()和listFiles()方法的使用,包括如何通过FilenameFilter和FileFilter筛选特定文件及文件夹,并提供了多个示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【1】list()方法

会返回一个字符数组,将制定路径下的文件或文件夹名字存储到String数组中。因为其返回的是一个String类型的数组,所以它也就只是一个名字而已(后面要讲到的listFiles()及其重载方法则不同,它们返回的是File类型的对象,所以具有其全部的属性和方法)。

有以下两种重载方式:

  • String[] list()

  • String[] list(FilenameFilter filter)

① String[] list(FilenameFilter filter)

FilenameFilter filter是一个目录过滤器,是一个接口。list(FilenameFilter filter)方法会选择符合条件的文件或文件夹。

源码如下:

public String[] list(FilenameFilter filter) {
	String names[] = list();
	if ((names == null) || (filter == null)) {
	    return names;
	}
	ArrayList v = new ArrayList();
	for (int i = 0 ; i < names.length ; i++) {
		/*通过accept方法判断,this指调用list的对象。。*/
	    if (filter.accept(this, names[i])) {
		v.add(names[i]);
	    }
	}
	return (String[])(v.toArray(new String[v.size()]));
    }

可知,list(FilenameFilter filter)方法保存的是那些能够使filter.accept()方法返回true的文件名。



使用时候需要重写accept方法

public interface FilenameFilter {
    /**
     * Tests if a specified file should be included in a file list.
     *
     * @param   dir    the directory in which the file was found.
     * @param   name   the name of the file.
     * @return  <code>true</code> if and only if the name should be
     * included in the file list; <code>false</code> otherwise.
     */
    boolean accept(File dir, String name);
}

1,实现FilenameFilter 接口

class FileNameFilter1 implements FilenameFilter{
		private Pattern pattern;
		
		/*传入正则表达式*/
		public FileNameFilter1(String regex) {
			pattern = Pattern.compile(regex);
		}
		
		@Override
		public boolean accept(File dir, String name) {
			boolean result = pattern.matcher(name).matches();
			return result;
		}
	}

2,采用匿名内部类的方式

class FileNameFilter2{
		public static FilenameFilter filter(final String regex){
		
			return new FilenameFilter(){
			
				private Pattern pattern = Pattern.compile(regex);

				@Override
				public boolean accept(File dir, String name) {
					return pattern.matcher(name).matches();
				}
			};
		}
	}

test

	@Test
	public void test2(){
		System.out.println("------挑选当前目录下以.开头的文件或文件夹-------");
		//1、挑选当前目录下以.开头的文件或文件夹,并且打印出来(创建一个类来实现FilenameFilter接口)
		File path = new File("./");
		String[] nameList = path.list(new FileNameFilter1("\\..*"));
		for(String itemName : nameList){
			System.out.println(itemName);
		}
		
		System.out.println("------挑选上级目录下以b开头的文件或文件夹-------");
		//2、挑选上级目录下以b开头的文件或文件夹,并且打印出来(使用匿名内部类的方式来实现)
		File path2 = new File("../");
		String[] nameList2 = path2.list(FileNameFilter2.filter("b.*"));
		for(String itemName : nameList2){
			System.out.println(itemName);
		}
		
		System.out.println("------挑选当前目录下以s开头的文件或文件夹-------");
		//3、将匿名内部类利用到极致
		File path3 = new File(".");
		String[] nameList3 = path3.list(
			new FilenameFilter(){//其实是在第二种方式的基础上精简过来的。
			private Pattern pattern = Pattern.compile("s.*");
			/*将path3 传给dir*/
			public boolean accept(File dir, String name) {
				return pattern.matcher(name).matches();
			}
		}
		);
		for(String itemName : nameList3){
			System.out.println(itemName);
		}
	}

result as follows :

------挑选当前目录下以.开头的文件或文件夹-------
.classpath
.myeclipse
.mymetadata
.project
.settings
------挑选上级目录下以b开头的文件或文件夹-------
book
book.zip
------挑选当前目录下以s开头的文件或文件夹-------
src


listFiles( ) :

list()和listFiles()方法的区别在于:

list()返回的是一个String类型数组,它只是一个数组,仅仅只是一个文件(文件夹)的名字而已;

而listFiles()方法返回的是一个File类的引用,它具有类的所有属性和方法,比如:String getName()方法就能够返回该文件的String类型的文件名(名字而已)。


下面的前三个方法返回File[]类型,第四个返回static File[]类型。

返回类型 :

该路径下所有文件或文件夹的绝对路径(pathname,注意File类型指的是路径,而不是文件)

1.listFiles()

2.listFiles(FileFilter filter)

3.listFiles(FilenameFilter filter)(上述讲过)

4.listRoots()
********************************************************************************************************************-
FileFilter接口的源代码:

public interface FileFilter {

    /**
     * Tests whether or not the specified abstract pathname should be
     * included in a pathname list.
     *
     * @param  pathname  The abstract pathname to be tested
     * @return  <code>true</code> if and only if <code>pathname</code>
     *          should be included
     */
    boolean accept(File pathname);

}

也要实现accept方法,但是传入的参数不一样,它是File类型的,而不是(File dir,String name)。这样的话就好办了。

    • 比如说,我要挑选文件夹:
class FileDirectory implements FileFilter{
	@Override
	public boolean accept(File pathname) {
		return pathname.isDirectory();
	}
}

    • 再比如说,我要挑选可执行文件:
class FileDirectory implements FileFilter{
	@Override
	public boolean accept(File pathname) {
		return pathname.canExecute();
	}
}

      • test
@Test
	public void test3(){
		System.out.println("-----判别当前目录下的文件是否为文件夹----");
		//1、列出当前目录下的所有文件和文件夹,保存为File类对象的数组,判别其是否为文件夹
		File path = new File(".");
		System.out.println(path.getAbsolutePath());
		
		File[] files = path.listFiles();
		for(File f : files){
			System.out.println(f + " ---> is a Directory? " + f.isDirectory());
		}
		
		System.out.println("-----挑选出当前目录下的所有文件夹----");
		//2、挑选出当前目录下的所有文件夹
		File path2 = new File(".");
		File[] files2 = path2.listFiles(new FileFilter(){
			public boolean accept(File pathname) {
				return pathname.isDirectory();
			}
		});
		for(File f : files2){
			System.out.println(f);
		}
		
		System.out.println("-----挑选出当前目录下的所有以s开头的文件夹----");
		//2、挑选出当前目录下的所有以s开头的文件夹
		File path3 = new File(".");
		File[] files3 = path3.listFiles(new FileFilter(){
			public boolean accept(File pathname) {
				Pattern pattern = Pattern.compile("s.*");
				return pathname.isDirectory()&&pattern.matcher(pathname.getName()).matches();
			}
		});
		for(File f : files3){
			System.out.println(f);
		}
		
		System.out.println("-----挑选出当前目录下的所有以.开头的文件夹,并且标明文件属性----");
		//3、挑选出当前目录下以.开头的文件或文件夹,并且在其后部标明f/d标明其为文件或文件夹
		File path4 = new File(".");
		File[] files4 = path4.listFiles(new FilenameFilter(){
			Pattern pattern = Pattern.compile("\\..*");
			public boolean accept(File dir, String name) {
				return pattern.matcher(name).matches();
			}
		});
		for(File f : files4){
			 String sfd = (f.isFile()) ? "file" : "dir";
			System.out.println(f.getName() + "---->" + sfd);
		}
	}

      • result as follows :
-----判别当前目录下的文件是否为文件夹----
C:\Users\12746\Workspaces\MyEclipse 8.5\JAVASE-6\.
.\.classpath ---> is a Directory? false
.\.myeclipse ---> is a Directory? true
.\.mymetadata ---> is a Directory? false
.\.project ---> is a Directory? false
.\.settings ---> is a Directory? true
.\2.jpg ---> is a Directory? false
.\dbcp.txt ---> is a Directory? false
.\dbcp2.txt ---> is a Directory? false
.\dbcp3.txt ---> is a Directory? false
.\dbcp4.txt ---> is a Directory? false
.\hello.txt ---> is a Directory? false
.\hello2.txt ---> is a Directory? false
.\src ---> is a Directory? true
.\WebRoot ---> is a Directory? true
-----挑选出当前目录下的所有文件夹----
.\.myeclipse
.\.settings
.\src
.\WebRoot
-----挑选出当前目录下的所有以s开头的文件夹----
.\src
-----挑选出当前目录下的所有以.开头的文件夹,并且标明文件属性----
.classpath---->file
.myeclipse---->dir
.mymetadata---->file
.project---->file
.settings---->dir

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流烟默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值