我有近500个档案。每个文件有近5个版本或10个版本,具有相同的名称。每个文件区别以文件名开头,后跟分号,然后是版本号。
示例:
检验.pdf; 1 检验.pdf; 2 Test.pdf; 3
所以我通过这样做获取文件列表:
File file = new File(Path + "\\");
File[] fileList = file.listFiles();
List<String> namesList = new ArrayList<String>();
for (int i = 0; i < fileList.length; i++) {
String name=fileList[i].getName();
if(name.contains(".pdf")||name.contains(".excel")){
namesList.add(name);
}
for (int i = 0; i < namesList.size(); i++) {
String name = namesList.get(i);
}
如何获得最高版本文件,即test.pdf; 3
答案 0 :(得分:3)
使用Map
将每个文件名映射到版本。迭代您的文件名,提取名称部分和版本部分,然后将版本与先前在地图中保存的版本进行比较。如果地图中没有名称版本,则将地图中的实际版本作为最高版本。
您可以尝试这样的事情:
@Test
public void listHighestVersion() {
String[] fileNames = {
"Test.pdf;1", "Test.pdf;2", "Test.pdf;3",
"Test.excel;1", "Test.excel;4", "Test.excel;3",
};
Map<String, Integer> fileVersionMap = new HashMap<>();
for(String fileNameWithVersion : fileNames) {
String[] split = fileNameWithVersion.split(";", 2);
if(split.length > 1) {
String fileName = split[0];
Integer fileVersion;
try {
fileVersion = Integer.parseInt(split[1]);
} catch(NumberFormatException e) {
fileVersion = 0;
}
Integer version = fileVersionMap.get(fileName);
if(version == null || fileVersion > version) {
fileVersionMap.put(fileName, fileVersion);
}
}
}
System.out.println(fileVersionMap);
}
输出是:
{Test.excel=4, Test.pdf=3}
答案 1 :(得分:1)
您可以使用以下代码:
String[] files = {"test.pdf;3","test.pdf;1","differentTest.pdf;2","test.pdf;5","test.pdf;4", "test.excel;3","test.excel;1","test.excel;6","test.excel;5","test.excel;4"};
HashMap <String, Integer> newestFiles = new HashMap<String, Integer>();
for (String currentString : files) {
String currentFileName = currentString.split(";")[0];
Integer currentFileVersion = Integer.parseInt(currentString.split(";")[1]);
if (newestFiles.containsKey(currentFileName)) {
if (newestFiles.get(currentFileName) < currentFileVersion) {
newestFiles.put(currentFileName, currentFileVersion);
}
}
else {
newestFiles.put(currentFileName, currentFileVersion);
}
}
for (Entry<String, Integer> maxValue : newestFiles.entrySet()) {
String result = new StringBuilder("Max version of file: ").append(maxValue.getKey()).append(" is: ").append( maxValue.getValue()).toString();
System.out.println(result);
}
结果:
Max version of file: test.excel is: 6
Max version of file: test.pdf is: 5
Max version of file: differentTest.pdf is: 2
这里做了什么:
else
声明中)。答案 2 :(得分:0)
FileDetail
的班级,其中包含2个属性,即字符串fileName
和整数version
作为属性。List<FileDetail>
namesList
comparable
实施comparator
或FileDetail
并实施排序逻辑。