1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17package org.apache.commons.io.filefilter;
18
19import java.io.File;
20import java.io.Serializable;
21
22/**
23 * This filter accepts files or directories that are empty.
24 * <p>
25 * If the <code>File</code> is a directory it checks that
26 * it contains no files.
27 * <p>
28 * Example, showing how to print out a list of the
29 * current directory's empty files/directories:
30 *
31 * <pre>
32 * File dir = new File(".");
33 * String[] files = dir.list( EmptyFileFilter.EMPTY );
34 * for ( int i = 0; i &lt; files.length; i++ ) {
35 *     System.out.println(files[i]);
36 * }
37 * </pre>
38 *
39 * <p>
40 * Example, showing how to print out a list of the
41 * current directory's non-empty files/directories:
42 *
43 * <pre>
44 * File dir = new File(".");
45 * String[] files = dir.list( EmptyFileFilter.NOT_EMPTY );
46 * for ( int i = 0; i &lt; files.length; i++ ) {
47 *     System.out.println(files[i]);
48 * }
49 * </pre>
50 *
51 * @since Commons IO 1.3
52 * @version $Revision: 587916 $
53 */
54public class EmptyFileFilter extends AbstractFileFilter implements Serializable {
55
56    /** Singleton instance of <i>empty</i> filter */
57    public static final IOFileFilter EMPTY = new EmptyFileFilter();
58
59    /** Singleton instance of <i>not-empty</i> filter */
60    public static final IOFileFilter NOT_EMPTY = new NotFileFilter(EMPTY);
61
62    /**
63     * Restrictive consructor.
64     */
65    protected EmptyFileFilter() {
66    }
67
68    /**
69     * Checks to see if the file is empty.
70     *
71     * @param file  the file or directory to check
72     * @return <code>true</code> if the file or directory
73     *  is <i>empty</i>, otherwise <code>false</code>.
74     */
75    public boolean accept(File file) {
76        if (file.isDirectory()) {
77            File[] files = file.listFiles();
78            return (files == null || files.length == 0);
79        } else {
80            return (file.length() == 0);
81        }
82    }
83
84}
85