遍历目录下的所有文件,同时获取文件的类型

遍历指定目录下的所有文件,同时获取文件的类型,即后缀名。

    public static void main(String[] args) {
        String pathName = "D:\\testPath";
        showFileName(pathName);
    }

     public static void showFileName(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File innerFile : files) {
                    if (innerFile.isDirectory()) {
                        System.out.println("文件夹:" + innerFile.getAbsolutePath());
                        showFileName(innerFile.getAbsolutePath());
                    } else {
                        System.out.println("文件:" + innerFile.getAbsolutePath());
                        String fileName = innerFile.getName();
                        //获取文件的后缀名
                        String suffix = fileName.substring(fileName.lastIndexOf("."));
                        System.out.println(fileName + ", suffix = " + suffix);
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }
posted @ 2021-07-17 15:30  楼兰胡杨  阅读(167)  评论(0编辑  收藏  举报