简体   繁体   中英

How do I get the most recent file based on a date in the filename?

I have a directory which contains files like this: {users_20221104.txt | users_20221105.txt | users_20221106.txt

dealers_20221104.txt | dealers_20221105.txt | dealers_20221106.txt |

nations_20221104.txt | nations_20221105.txt | nations_20221106.txt }

I need to retrieve only the last file of each occurence, which means users_20221106, dealers_20221106 and nations_20221106

At the moment I have something like this:

    private void downloadFiles()  {
        List<String> filesPath = ftpClient.listFiles(ftpFolderIn);
        String usersFileTxt = null;
        String dealerFileTxt = null;
        String nationFileTxt = null;
        
        for (String filepath : filesPath) {
            if (filepath.contains("users")) {
                usersFileTxt = filepath;
            }
            if (filepath.contains("dealers")) {
                dealerFileTxt = filepath;
            }
            if (filepath.contains("nations")) {
                nationFileTxt = filepath;
            }
        }
        usersFile = ftpClient.downloadFile(usersFileTxt);
        dealerFile = ftpClient.downloadFile(dealerFileTxt);
        nationFile = ftpClient.downloadFile(nationFileTxt);
    }

Loop through your file names.

Extract the date portion. One way to do this is to use methods on String class such as split and replace .

Parse the date portion as a LocalDate . Use the predefined formatter for parsing the “basic” (condensed) version of the standard ISO 8601 format.

LocalDate ld = LocalDate.parse( input , DateTimeFormatter.BASIC_ISO_DATE ) ;

Compare the dates using their natural ordering, with isBefore , isAfter , and isEqual . Remember which file has the latest date as you loop.

A clean approach would be to create a Compartor and use the same with the stream by initializing it with corresponding prefixes.

Demo :

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

class FilesComparator implements Comparator<String> {
    private String prefix;

    FilesComparator(String prefix) {
        this.prefix = prefix;
    }

    @Override
    public int compare(String s1, String s2) {
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("'" + prefix + "'uuuuMMdd'.txt'");
        LocalDate ldt1 = LocalDate.parse(s1, parser);
        LocalDate ldt2 = LocalDate.parse(s2, parser);
        return ldt1.compareTo(ldt2);
    }
}

public class Main {
    public static void main(String[] args) {
        List<String> files = List.of(
                "users_20221104.txt", "users_20221106.txt", "users_20221105.txt",
                "dealers_20221104.txt", "dealers_20221106.txt", "dealers_20221105.txt",
                "nations_20221104.txt", "nations_20221106.txt", "nations_20221105.txt");

        String usersFileTxt = getLatestFile(files, "users_").get();
        System.out.println(usersFileTxt);

        String dealersFileTxt = getLatestFile(files, "dealers_").get();
        System.out.println(dealersFileTxt);

        String nationsFileTxt = getLatestFile(files, "nations_").get();
        System.out.println(nationsFileTxt);
    }

    static Optional<String> getLatestFile(List<String> files, String prefix) {
        return files.stream()
                .filter(filename -> filename.startsWith(prefix))
                .max(new FilesComparator(prefix));
    }
}

Output :

users_20221106.txt
dealers_20221106.txt
nations_20221106.txt

Learn more about the modern Date-Time API from Trail: Date Time

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