| Author |
Checking for a file name with a date/timestamp mask
|
Tim Vries
Greenhorn
Joined: Nov 29, 2001
Posts: 8
|
|
I have files posted to a directory on a daily/weekly basis that have a date and/or timestamp as part of the filename. For example, myfile02142002.txt. The file name will always have the same "stem" (i.e., myfile in this case) but the date/timestamp will be different. In my database, I have 2 fields that are used to build the file name format to be read: path = /usr/home/ name = myfilemmddyyyy.txt The application builds the file path to locate as "/usr/home/myfilemmddyyyy.txt". However, the actual file name is "/usr/home/myfile02142002.txt". Is there an easy way to find all of the files that match this format?
|
 |
Les Dsouza
Greenhorn
Joined: Jan 29, 2002
Posts: 27
|
|
You can try using the FilenameFilter, see the code below. Hope it is helpful...
|
 |
Tim Vries
Greenhorn
Joined: Nov 29, 2001
Posts: 8
|
|
Got it to work with the following augmentation to your suggestion. Returns a string of the most recent file which matches the pattern. (fileName contains a regular expression pattern - "myfile[0-9][0-9]-[0-9][0-9]-[0-9][0-9].csv") import java.io.*; import org.apache.regexp.RE; import org.apache.regexp.RESyntaxException; public class FileListHelper { public static String getFileMatch(String path, String filename){ final String dirPath = path; final String fileName = filename; FilenameFilter filter=new FilenameFilter(){ public boolean accept(File dir, String name) { try{ RE regex = new RE(fileName,regex.MATCH_CASEINDEPENDENT); boolean matched = regex.match(name); if (matched) { return true; } }catch (RESyntaxException e){ System.out.println("Error comparing Regexp: " + e); } return false; } }; File f = new File(dirPath); File fl[] = f.listFiles(filter); int i = 0; String oldestFile = ""; try{ long prevMod = 0; long lastMod = 0; while (fl[i].exists()){ prevMod = lastMod; lastMod = fl[i].lastModified(); if (lastMod > prevMod) { oldestFile = fl[i].toString(); } i++; } }catch (ArrayIndexOutOfBoundsException e){ } return oldestFile; } }
|
 |
 |
|
|
subject: Checking for a file name with a date/timestamp mask
|
|
|