java项目实践一:目录文件遍历

能实现指定目录下指定类型的文件遍历

package util;
import java.io.File;
import java.io.IOException;

/* INPUT: directory, file type
 * OUTPUT: file names of file type
 */
public class test{
    public static void main(String[] args) throws IOException {
        util.listDirectory(new File("D:\\Hallieping\\documents\\新文献\\fake news"), ".pdf");
    }
}
package util;

// java实践1 遍历目录
import java.io.File;
import java.io.IOException;

public class util {
    public static void listDirectory(File dir, String fileType) throws IOException {
        if( !dir.exists())
            throw new IllegalArgumentException("The directory :" + dir +" doesn't exist.");
        if( !dir.isDirectory())
            throw new IllegalArgumentException( dir + "is not a directory !");

        File[] list = dir.listFiles();
        // list all files including directories in dir;
        if(list != null && list.length > 0) {
            for(File file: list) {
                if(file.isDirectory()) {
                    listDirectory(file, fileType);
                    // if it is a sub-directory, recur;
                }
                else {
                    if(file.isFile() && file.getName().endsWith(fileType)) {// print the right files' names;
                        System.out.println(file.getName());
                    }
                }
            }
        }
    }

}

细节错误:

1.方法 throws IOException{}
内部 throw ...Exception
2.printlin 全小写
3.文件全都放在package util下面,并且都在src下面

全部评论

相关推荐

秋招投简历提醒助手:一开始还觉得是正常交流。直到一看薪资4-6😨
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务