简体   繁体   中英

Read Multiple Files In Java

I want to read multiple files into Java at once. File names are like:

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

There are over 1,000 files and I do not want to write all files names in Java one by one, using code similar to the following one:

String fileNames = {"nnnnn_UM2012.txt","ghkjdf_UM2045.txt","erey_UM2189.txt", …}

Maybe the filenames should be read in reverse order. How can I do that?

To get all files in a folder (sub-folders are included in the list of files):

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

To get all files in a folder, excluding sub-folders:

    // 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();
        }
    }));

To sort the list of files into reverse case-sensitive order:

    // 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());
        }
    });

To sort the list of files into reverse case-insensitive order:

    // 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());
        }
    });

您可以使用listFiles方法获取文件夹中的所有文件。

File rep = new File("path to rep");
File[] list = rep.listFiles();
ArrayList<String> filenames = new ArrayList<String>();
for ( int i = 0; i < list.length; i++) {
    filenames.add(list[i].getName());
} 

I guess it can be a solution to your problem.

You can follow the below approach if all the files are in a single directory. Get a reference to the directory by providing its fully qualified path and then use the list() function get all the file names into a String array inside the directory.

After this step you can sort the files according to the way you want (For eg by its name,length,etc..).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM