lundi 7 août 2017

Sort file list by name and date

I have a text file that I can access & open a directory. This directory contains csv files. Please refer:

export_test_practise-1_2017-06-23_2017-06-23.csv
export_test_practise-1_2017-06-24_2017-06-24.csv
export_test_practise-2_2017-06-24_2017-06-24.csv

Now I want to write a number in the second line of the text file (String nString). This number then calls the corresponding csv file. If several csv files end with the same number, I always want to call the most recent. For example: file.txt has a 1 -> open export_test_practise-1_2017-06-24_2017-06-24.csv (practise-1 with lastModiefiedDate) Whats the best way to do this?

public class Test{
private static void sortFilesByName(File txtFile)
    throws IOException
{
    // Read from the file
    BufferedReader br = new BufferedReader(new FileReader(txtFile));
    String path = br.readLine();
    String nrString = br.readLine();
    br.close();
    File[] fileList = new File(path).listFiles(); 
    // Sort files by name
    Arrays.sort(fileList); 

long mod = 0;
File found = null;
System.out.println("nrString: " + nrString);
for (File f : fileList)
{
    System.out.println(f.getName());

    boolean fileNameOkForNrString = true;
    if (fileNameOkForNrString && f.lastModified() > mod)
    {
        mod = f.lastModified();
        found = f;
    }
}

} }

Aucun commentaire:

Enregistrer un commentaire