在 Java 中读取多个文件

use*_*487 3 java filenames readfile

我想一次将多个文件读入 Java。文件名类似于:

  • nnnnn_UM2012.txt
  • ghkjdf_UM2045.txt
  • erey_UM2189.txt
  • ....

有1000多个文件,我不想用Java一一写所有文件名,使用类似于以下代码的代码:

String fileNames = {"nnnnn_UM2012.txt","ghkjdf_UM2045.txt","erey_UM2189.txt", …}
Run Code Online (Sandbox Code Playgroud)

也许应该以相反的顺序读取文件名。我怎样才能做到这一点?

Ste*_*eod 5

要获取文件夹中的所有文件(子文件夹包含在文件列表中):

    // get all files in the folder
    final File folder = new File(".");
    final List<File> fileList = Arrays.asList(folder.listFiles());
Run Code Online (Sandbox Code Playgroud)

要获取文件夹中的所有文件,不包括子文件夹:

    // get all files in the folder excluding sub-folders
    final File folder = new File(".");
    final List<File> fileList = Arrays.asList(folder.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.isFile();
        }
    }));
Run Code Online (Sandbox Code Playgroud)

要将文件列表排序为区分大小写的反向顺序:

    // sort the files into reverse order
    Collections.sort(fileList, new Comparator<File>() {
        public int compare(File o1, File o2) {
            return o2.getName().compareTo(o1.getName());
        }
    });
Run Code Online (Sandbox Code Playgroud)

要将文件列表排序为不区分大小写的反向顺序:

    // sort the files into reverse order ignoring case
    Collections.sort(fileList, new Comparator<File>() {
        public int compare(File o1, File o2) {
            return o2.getName().compareToIgnoreCase(o1.getName());
        }
    });
Run Code Online (Sandbox Code Playgroud)