我有一堆带有名称的文件
32f245bb02abd408a6f0e997640f7e84d3cdf0e4May 2, 2016.java
a5c3fc386ee6ff7259f4004128baff8a961ec804May 3, 2016.java
eaefc7552ab8ce39ea26272f995476869ed91e1aMay 3, 2016.java
我想用日期(在文件名中)排列它们。我使用正则表达式从文件名中提取日期并对它们进行排序,但现在我只能根据日期对文件进行排序。我尝试重命名文件,但日期重复并且无法使用创建/修改/访问日期,因为所有日期都是相同的。
File directory2 = new File("path to files");
String newfile="";
Set<String> source= new HashSet<String>();
ArrayList<String> datestring=new ArrayList<String>();
try (Stream<Path> paths = Files.walk(Paths.get(directory2.toString()))) {
paths.skip(1)
.forEach(s->{source.add(s.toString());});
} catch (IOException e) {
e.printStackTrace();
}
for(Iterator<String> it=source.iterator(); it.hasNext();) {
newfile = it.next().toString();
File f = new File(newfile);
String Date = f.getName();
String regex2 = "((?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Sept|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?))(\\s+)(\\d+)(,)(\\s+)((?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])";
Pattern pattern2 = Pattern.compile(regex2,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m2 = pattern2.matcher(Date);
while(m2.find()) {
String file= m2.group(0);
datestring.add(file);
}
}
Collections.sort(datestring, new Comparator<String>() {
DateFormat f = new SimpleDateFormat("MMM dd, yyyy");
@Override
public int compare(String o1, String o2) {
try {
return f.parse(o1).compareTo(f.parse(o2));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
});
}
我尝试在提取日期后重命名文件,如下所示,但如果日期重复,则无法重命名它们,并且仍然无法根据日期对它们进行排序。
for(Iterator<String> it=source.iterator(); it.hasNext();) {
newfile = it.next().toString();
File f = new File(newfile);
String Date = f.getName();
for (String datematch:datestring) {
if(Date.contains(datematch)) {
f.renameTo(new File("path to new directory"+datematch+".java"));
}
}
}
最佳答案
下面是 Java 8 中的代码,用于根据文件名上的日期对文件进行排序。
public static void main(String[] args) throws IOException {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.ENGLISH);
try (Stream<Path> filesStream = Files.list(Paths.get("/tmp/stackoverflow-files"))) {
List<String> files = filesStream.map(Path::getFileName)
.map(Path::toString)
.map(filename -> new Pair<>(filename, filename.substring(40).replace(".java", "")))// The hash seems to be fixed of size 40
.map(fileAndDate -> new Pair<>(fileAndDate.getKey(), LocalDate.parse(fileAndDate.getValue(), dateFormatter)))
.sorted(Comparator.comparing(Pair::getValue))
.map(Pair::getKey)
.collect(Collectors.toList());
System.out.println(files);
}
}
代码的作用:
- 获取路径上的所有文件
- 获取文件名
- 保留文件名并操作它的副本以通过以下方式获得 localDate:
- 删除哈希值(显然大小为 40)
- 删除 .java
- 转换为 LocalDate
- 按本地日期排序
- 仅返回按日期排序后的文件名列表
- 打印文件列表
输出:
[32f245bb02abd408a6f0e997640f7e84d3cdf0e4May 2, 2016.java, eaefc7552ab8ce39ea26272f995476869ed91e1aMay 3, 2016.java, a5c3fc386ee6ff7259f4004128baff8a961ec804May 3, 2016.java]
关于java - 使用文件名中的日期对文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55381296/