java读取某个目录下的所有文件

java读取某个目录下的单个文件,比较简单;如果某个目录下有很多个文件,需要用java一次性全部读出来,该怎么办呢?

今天我们以读取NC文件为例,一次性读取某个目录下的所有文件;

首先在循环读取文件列表:如果是目录,则目录路径+文件名;如果不是目录,则直接输出文件名

package jichu2.duowenjian;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFile {
    public ReadFile() {
    }
    /**
     * 读取某个文件夹下的所有文件
     */
    public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
        try {
            File file = new File(filepath);
            if (!file.isDirectory()) {
                System.out.println("文件");
                System.out.println("path=" + file.getPath());
                System.out.println("absolutepath=" + file.getAbsolutePath());
                System.out.println("name=" + file.getName());

            } else if (file.isDirectory()) {
                System.out.println("文件夹");
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "\\" + filelist[i]);
                    if (!readfile.isDirectory()) {
                        System.out.println("path=" + readfile.getPath());
                        System.out.println("absolutepath="
                                + readfile.getAbsolutePath());
                        System.out.println("name=" + readfile.getName());

                    } else if (readfile.isDirectory()) {
                        readfile(filepath + "\\" + filelist[i]);
                    }
                }

            }

        } catch (FileNotFoundException e) {
            System.out.println("readfile()   Exception:" + e.getMessage());
        }
        return true;
    }
}

然后在主函数中定义方法的文件夹路径:

我在SubsetSpatialRegion文件夹下存放了多个NC文件,所以我的路径为 F:/SubsetSpatialRegion
package jichu2.duowenjian;

import java.io.FileNotFoundException;
import java.io.IOException;

import static jichu2.duowenjian.ReadFile.readfile;

public class Demo {
    public static void main(String[] args) {
        try {
            readfile("F:/SubsetSpatialRegion");
        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        }
        System.out.println("ok");
    }
}

运行结果:

猜你喜欢

转载自blog.csdn.net/m0_37501154/article/details/88315037