0

我想在文件夹中搜索名称以“_1.xml”结尾的文件(UNIX 文件系统,我正在搜索 /home/myuser/myfolder/)。我想避免使用 svn 文件夹:我不知道它们是否会给我错误,这就是我想避免它们的原因。如果你向我保证他们是安全的,我不介意他们。

我的代码如下:

/**
 * 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;
}

也尝试过这样的 FilenameFilters:

        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);
        }

无论如何我都会遇到异常:

    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)

     ...

有什么帮助吗?

4

1 回答 1

1

我还没有尝试过,但以下代码段应该适合您的需求:

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;
}

来电:

List<File> found = search(new File("/home/myuser/myfolder"), 1);
于 2013-01-14T10:39:07.797 回答