面试题求解:列举文件或者文件夹
 
有人问及一个用java列举某个文件夹下所有的文件或者目录编程题。结果他不加思索的写了十几行代码,就搞定了,结果面试官说等通知,直到最后都没通知他,我猜想出题人的最终想法是看如何封装代码,如何灵活使用丰富的API。
 
于是我试着写一个可选择结果,希望对各位有用
 
import java.io.File;
import java.io.FileFilter;

/**
* 如何列出某个目录下的所有文件/目录
*
* @author leizhimin 2010-3-22 20:58:37
*/

public class FileTest {
        public static final byte TYPE_ALL = 0;            //所有的文件和文件夹
        public static final byte TYPE_FILE = 1;         //文件
        public static final byte TYPE_DIR = 2;            //文件夹

        public static void main(String args[]) {
                File[] flist = listFile("C:\\", FileTest.TYPE_FILE);
                for (File file : flist) {
                        System.out.println(file.getPath());
                }
        }

        /**
         * 列举文件或者目录
         *
         * @param path 操作目录
         * @param type 列举的类型
         * @return 所列举的文件或文件夹列表
         */

        public static File[] listFile(String path, byte type) {
                File[] result = null;
                File f = new File(path);
                switch (type) {
                        case TYPE_ALL:
                                result = f.listFiles();
                                break;
                        case TYPE_FILE:
                                result = f.listFiles(new MyFileFilter(true));
                                break;
                        case TYPE_DIR:
                                result = f.listFiles(new MyFileFilter(false));
                                break;
                        default:
                                result = f.listFiles();
                }
                return result;
        }
}

/**
* 文件过滤器
*/

class MyFileFilter implements FileFilter {
        //过滤所要保留的类型是否是文件
        private boolean isFile = true;

        MyFileFilter(boolean isFile) {
                this.isFile = isFile;
        }

        public boolean accept(File pathname) {
                if (isFile) {
                        if (pathname.isFile()) return true;
                        return false;
                } else {
                        if (pathname.isDirectory()) return true;
                        return false;
                }
        }
}
 
输出结果:
C:\bootfont.bin
C:\ntldr
C:\NTDETECT.COM
C:\CONFIG.SYS
C:\AUTOEXEC.BAT
C:\IO.SYS
C:\MSDOS.SYS
C:\GHLDR
C:\boot.ini
C:\锦衣卫TC国语中字修正声音甄子丹赵薇2010最新动作大片.rmvb
C:\The.Hurt.Locker.2008.拆弹部队.双语字幕.HR-HDTV.AC3.1024x544.x264-人人影视.mkv
C:\Linux程序设计(第三版)_3of2.rar
C:\Linux程序设计(第三版)_3of1.rar
C:\Linux程序设计(第三版)_3of3.rar
C:\Linux程序设计(第三版)_目录.rar
C:\4.txt

Process finished with exit code 0
 
其实,有时候猜不中出题人的意图也会很失败的,呵呵!