【Java】FileUtils-获取路径的所有文件(或文件夹)

一、获取指定路径下的所有Excel文件

package com.boulderaitech.utils;

import java.io.File;
import java.util.Arrays;

public class FileUtil {
    public static void main(String[] args) {
        String path = "C:\\Users\\xxljob\\Desktop\\sage字段表";
        // Arrays.stream(getFileNameArray(new File(path))).forEach(System.out::println);
        Arrays.stream(getFileNameArray(new File(path))).forEach(x->{
            String[] replacedPath = x.replace('\\', '@').split("@");
            String fileName = replacedPath[replacedPath.length - 1];
            String fileNameWithoutSuffix = fileName.split(".xlsx")[0];
            System.out.println(fileNameWithoutSuffix);
        });
    }

    public static String[] getFileNameArray(File file) {
        return Arrays.stream(file.listFiles(pathname -> pathname.isFile())).map(x -> String.valueOf(x)).toArray(String[]::new);
    }
}

二、获取路径下的文件和文件夹

File file = new File(path);
String [] fileName = file.list();

三、递归获取目录下的子目录和文件

 public static void getAllFileName(String path, ArrayList<String> fileName)
    {
        File file = new File(path);
        File [] files = file.listFiles();
        String [] names = file.list();
        if(names != null)
            fileName.addAll(Arrays.asList(names));
        for(File a:files)
        {
            if(a.isDirectory())
            {
                getAllFileName(a.getAbsolutePath(),fileName);
            }
        }
    }
    //遍历fileName

参考:https://www.csdn.net/tags/Mtjakg3sNzY3NTUtYmxvZwO0O0OO0O0O.html

posted @ 2022-08-31 18:35  哥们要飞  阅读(2418)  评论(0编辑  收藏  举报