I want to search for files with its name ending in "_1.xml" into a folder (UNIX filesystem, I'm searching into /home/myuser/myfolder/). I would like to avoid svn folders: I don't know if they can give me errors, that's why I want to avoid them. If you asure me they are safe, I don't mind about them.
My code is the following one:
/**
* Searches associated XML file "WHATEVER_id.xml" given an id
*
* @param id
* notam id
*
* @return absolute path to XML file
*
*/
public String getXMLFileFromID(final int id) {
String path = null;
File root;
try {
root = new File("/home/myuser/myfolder");
String[] extensions = {"xml"};
boolean recursive = true;
try{
Collection<File> files = FileUtils.listFiles(root, extensions, recursive);
for(Iterator<File> iterator = files.iterator(); iterator.hasNext(); ){
File file = (File) iterator.next();
if(file.getName().endsWith(Integer.toString(id) + ".xml")){
path = file.getAbsolutePath();
LoggerFactory.getLogger(FTPDatabase.class).info("getXMLFileFromID : Found associated XML file in " + path);
return path;
}
}
}catch(Exception e){
e.printStackTrace();
}
LoggerFactory.getLogger(FTPDatabase.class).info("getXMLFileFromID : Unable to find XML associated to id " + id);
} catch (DatabaseException e) {
LoggerFactory.getLogger(FTPDatabase.class).info("getXMLFileFromID : DatabaseException : " + e.getMessage());
}
return path;
}
Also have tried with FilenameFilters like this:
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(Integer.toString(id) + ".xml");
}
});
if(matchingFiles.length == 1){
path = matchingFiles[0].getAbsolutePath();
LoggerFactory.getLogger(FTPDatabase.class).info("getXMLFileFromID : Found associated XML file in " + path);
}
else{
LoggerFactory.getLogger(FTPDatabase.class).info("getXMLFileFromID : Unable to find XML associated to NOTAM id " + id);
}
Any way I'm getting exception:
java.lang.IllegalArgumentException: Parameter 'directory' is not a directoy,
at org.apache.commons.io.FileUtils.validateListFileParameters (545)
at org.apache.commons.io.FileUtils.listFiles(521)
at org.apache.commons.io.FileUtils.listFiles(691)
at com.core.ftp.FTPDataBase.getXMLFileFromID(227) (that's the FileUtils.listFiles
line)
...
Any help?
I haven't tried yet, but the following snippet should suit your needs:
public List<File> search(File root, int id) {
List<File> found = new ArrayList<File>();
if (root.isFile() && root.getName().endsWith("_" + id + ".xml")) {
found.add(root);
} else if (root.isDirectory() && !root.getName().contains("svn")) {
for (File file : root.listFiles()) {
found.addAll(search(file, id));
}
}
return found;
}
Calling:
List<File> found = search(new File("/home/myuser/myfolder"), 1);