IntelliJ Java IDE
The moose likes I/O and Streams and the fly likes Checking for a file name with a date/timestamp mask Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Reply Bookmark "Checking for a file name with a date/timestamp mask" Watch "Checking for a file name with a date/timestamp mask" New topic
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;
}
}
 
IntelliJ Java IDE
 
subject: Checking for a file name with a date/timestamp mask
 
Threads others viewed
add timestamp with .txt file & write some information to the .txt file
Help required to log messages in tomcat :"Not able to log messages to separate files"
how to read file name which contains space?
How to access java beans
Commons net Ftpclient listfiles problem
developer file tools