Ale*_*tin 5 java directory file
按上次修改日期获取文件的最快方法是什么?我有一个包含一些 txt 文件的目录。用户可以按日期进行研究,我按上次修改日期(在 File[] 中)列出目录中的所有文件,并搜索具有特定日期的正确文件。我使用最后修改日期的集合排序来对我的文件进行排序。当我从本地驱动器获取文件时,速度很快,但当我想访问网络(专用网络)上的驱动器时,可能需要大约 10 分钟才能获取文件。我知道我不能比网络更快,但是有没有一个解决方案可以比我的解决方案更快?
我的代码示例:
File[] files = repertoire.listFiles();
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return Long.valueOf(o2.lastModified()).compareTo(o1.lastModified());
}
});
for (File element : files) {
// i get the right file;
}
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助
这是解决方案:
Path repertoiry = Paths.get(repertoire.getAbsolutePath());
final DirectoryStream<Path> stream = Files.newDirectoryStream(repertoiry, new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis() >= (dateRechercheeA.getTime() - (24 * 60 * 60 * 1000)) && Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis() <= (dateRechercheeB.getTime() + (24 * 60 * 60 * 1000));
}
});
for (Path path : stream) {
if (!path.toFile().getName().endsWith("TAM") && !path.toFile().getName().endsWith("RAM")) {
listFichiers.add(path.toFile());
}
}
Run Code Online (Sandbox Code Playgroud)
使用 java 7 NIO 包,可以过滤目录以仅列出所需的文件。
(警告DirectoryStreams不要迭代子目录。)
Path repertoire = Paths.get("[repertoire]");
try ( DirectoryStream<Path> stream = Files.newDirectoryStream(repertoire, new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis() = [DATE_SEARCHED (long)]
}
})){
for (Path path : stream) {
// Path filtered...
}
}
Run Code Online (Sandbox Code Playgroud)
通常,此解决方案比创建完整的文件列表、对列表进行排序,然后迭代列表以找到正确的日期提供更好的性能。
用你的代码:
//use final keyword to permit access in the filter.
final Date dateRechercheeA = new Date();
final Date dateRechercheeB = new Date();
Path repertoire = Paths.get("[repertoire]");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(repertoire, new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
long entryDateDays = Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).to(TimeUnit.DAYS);
return !entry.getFileName().endsWith("TAM") //does not take TAM file
&& !entry.getFileName().endsWith("RAM") //does not take RAM file
&& ((dateRechercheeB == null && Math.abs(entryDateDays - TimeUnit.DAYS.toDays(dateRechercheeA.getTime())) <= 1)
|| (dateRechercheeB != null && entryDateDays >= (TimeUnit.DAYS.toDays(dateRechercheeA.getTime()) - 1) && entryDateDays <= (TimeUnit.DAYS.toDays(dateRechercheeA.getTime()) + 1)));
}
})) {
Iterator<Path> it = stream.iterator();
//Iterate good file...
}
Run Code Online (Sandbox Code Playgroud)
过滤器是直接在接受方法中而不是之后进行的。
JAVA SE 7 - 文件 - newDirectoryStream()
| 归档时间: |
|
| 查看次数: |
2512 次 |
| 最近记录: |