Reputation: 337
I have a directory which contains files in the following format. The files are in a diretory called /incoming/external/data
ABC_20100806.csv
ABC_20100807.csv
ABC_20100808.csv
ABC_20100809.csv
ABC_20100810.csv
ABC_20100811.csv
ABC_20100812.csv
As you can see the filename of the file includes a timestamp. i.e. [RANGE]_[YYYYMMDD].csv
What i need to do is find out which of these files has the newest date using the timestamp on the filename not the system timestamp and store the filename in a variable and move it to another directory and move the rest to a different directory in java.
Upvotes: 0
Views: 3044
Reputation: 23637
You can read the filenames into an array using:
File directory = new File("/incoming/external/data");
String[] fileNames = directory.list(new FilenameFilter() {
public boolean accept(File dir, String fileName) {
return fileName.endsWith(".csv");
}
});
And from there simply sort the array if your files always have the same prefix:
Arrays.sort(fileNames);
One way you can remove the prefix and suffix of each fileName to extract the date is:
int underline = fileName.indexOf("_");
int dot = fileName.indexOf(".");
String datePart = fileName.substring(underline, dot);
And then you can add that string to an array and sort (lexically).
If for some other reason you want to convert the dates into Java Dates, you can use:
SimpleDateFormat dt = new SimpleDateFormat("yyyymmdd");
Date date = dt.parse(datepart);
And you'll have a Java date, which you can also sort in an array or list.
Upvotes: 3