如何将File []的元素与对象列表中每个元素的名称进行比较

时间:2015-01-07 00:30:10

标签: java

我需要知道目录中的哪些文件不在我的列表中。代码如下,问题是我不知道如何比较它们。

*比较仅基于文件名。

File dir = new File(directory);
File[] files = dir.listFiles(); 

List<Records> myFiles; 
for(int i=0;i<myFiles.size();i++){
            System.err.println(myFiles.get(i).getDetails().getName());
}

正如您所看到的,我有一个File []类型的列表,其中包含目录中所有文件的列表。 还有一个包含所有记录对象的List类型列表。

2 个答案:

答案 0 :(得分:1)

除了从files列表中的myFiles数组中查找每个文件名之外,您没有什么不同。

你尝试了什么,你遇到了什么问题?无论如何,这是一个快速实现的方法。

/**
 * Returns a set of files in the {@code filesInDir} that are not included in the {@code myFiles} list.
 * 
 * <p>
 * Does a case insensitive comparison of file names to confirm presence.
 * 
 * @param filesInDir the files in a given directory
 * @param myFiles my list of files
 * @return files in the {@code filesInDir} that are not included in the {@code myFiles} list
 */
Set<File> filesNotIncludedInMyList(File[] filesInDir, List<Record> myFiles) {
    Set<File> filesNotInMyList = new HashSet<>();
    for (File fileInDirectory : filesInDir) {
        boolean fileInDirectoryIncludedInMyList = false;
        for (Record myFile : myFiles) {
            if (fileInDirectory.getName().equalsIgnoreCase(myFile.getDetails().getName())) {
                fileInDirectoryIncludedInMyList = true;
            }
        }
        if (! fileInDirectoryIncludedInMyList) {
            filesNotInMyList.add(fileInDirectory);
        }
    }

    return filesNotInMyList;
}

这是一个更加可读的版本,没有嵌套的for循环。当然,这会进行不区分大小写的搜索(通过降低所有文件名的大小),但如果需要,可以执行区分大小写的搜索。

/**
 * Returns files in the {@code filesInDir} that are not included in the {@code myFiles} list.
 * 
 * <p>
 * Does a case insensitive comparison of file names to confirm presence.
 * 
 * @param filesInDir the files in a given directory
 * @param myFiles my list of files
 * @return files in the {@code filesInDir} that are not included in the {@code myFiles} list
 */
Set<File> filesNotIncludedInMyList(File[] filesInDir, List<Record> myFiles) {
    Set<File> filesNotInMyList = new HashSet<>();
    Set<String> myFileNames = recordFileNames(myFiles);
    for (File fileInDirectory : filesInDir) {
        if (! myFileNames.contains(fileInDirectory.getName().toLowerCase())) {
            filesNotInMyList.add(fileInDirectory);
        }
    }

    return filesNotInMyList;
}

/**
 * Creates a set containing the file names of all the records in the given list of records.
 * 
 * @param myFiles my list of files
 * @return a set containing the file names of all the records in the given list of records
 */
Set<String> recordFileNames(List<Record> myFiles) {
    Set<String> recordFileNames = new HashSet<>();
    for (Record file : myFiles) {
        recordFileNames.add(file.getDetails().getName().toLowerCase());
    }
    return recordFileNames;
}

答案 1 :(得分:0)

正如代码所示List myFiles尚未初始化,所以你必须首先初始化这个列表然后你可以做你想要的所有......