简体   繁体   English

? 如何在不使用 stream 的情况下列出目录或驱动器中的所有文件并仅使用 java 中的 nio api 按创建日期对其进行排序

[英]? How can I list all files in directory or drive without using stream and sort it by creation date using just nio api in java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Explorateur {
    public void Fichiers(String chemin) throws IOException {
        Path disque=Paths.get(chemin);
        try (Stream<Path> paths=Files.walk(disque, Integer.MAX_VALUE)) {
            paths.filter(Files::isRegularFile)
                 .forEach(System.out::println);
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

How can I do it without using Stream and sort it by creation date using just NIO?如果不使用 Stream 并仅使用 NIO 按创建日期对其进行排序,我该如何做到这一点?

At first I need to check if a specific file is there.首先,我需要检查是否存在特定文件。 The second function is to sort all files by creation date.第二个 function 是按创建日期对所有文件进行排序。

I think that I should return a collection of files and creation date then sort it.我认为我应该返回一组文件和创建日期,然后对其进行排序。

You just collect the Stream into a collection like Set , SortedSet or List :您只需将Stream收集到SetSortedSetList之类的集合中:

TreeSet<Path> paths = Files.walk(path).collect(Collectors.toCollection(TreeSet::new));
if (paths.contains(a)) {
  // checked for presence
}
// if you want to sort the files right away
List<File> files = Files.walk(path)
                        .map(Path::toFile)
                        .sorted(Comparator.comparing(File::lastModified))
                        .collect(Collectors.toList());

I don't think creation date is something you can find from the file api.我不认为您可以从文件 api 中找到创建日期。

This example works using FileVisitor .此示例使用FileVisitor工作。 It is longer than stream examples, but will be quicker on very large directory structures as FileVisitor provides BasicFileAttributes so avoids file IO calls in sort.它比 stream 示例长,但在非常大的目录结构上会更快,因为FileVisitor提供了 BasicFileAttributes,因此避免了文件 IO 调用排序。

Plus you can sort by name, creation, modified times etc:另外,您可以按名称、创建、修改时间等进行排序:

public class ExampleFileVisitor
{
    public static void main(String[] args) throws IOException
    {
        Path dir = Path.of(args[0]);
        long start = System.currentTimeMillis();

        HashMap<Path,BasicFileAttributes> pathAttrs = scan(dir);

        ArrayList<Path> paths = new ArrayList<>(pathAttrs.keySet());
        Collections.sort(paths,  Comparator.comparing(p -> pathAttrs.get(p).lastModifiedTime()));
        // Collections.sort(paths,  Comparator.comparing(p -> pathAttrs.get(p).creationTime()));
        // Collections.sort(paths,  Comparator.comparing(Path::getFileName));

        List<Path> top5 = paths.subList(0, Math.min(5, paths.size()));
        long elapsed = System.currentTimeMillis() - start;
        System.out.println("DONE "+dir+" SIZE "+paths.size()+" in "+elapsed+"ms");
        for (Path f : top5)
            System.out.println("Found "+f);
    }

    private static HashMap<Path, BasicFileAttributes> scan(Path dir) throws IOException
    {
        HashMap<Path,BasicFileAttributes> pathAttrs = new HashMap<>();
        FileVisitor<Path> visitor = new FileVisitor<>() {
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException  {
                return FileVisitResult.CONTINUE;
            }
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                pathAttrs.put(file, attrs);
                return FileVisitResult.CONTINUE;
            }
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                throw exc;
            }
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        };
        //visitor = Delegate.create(visitor, FileVisitor.class);
        Files.walkFileTree(dir, visitor);
        return pathAttrs;
    }
}

I think you can tell I've been in lockdown too long.我想你可以看出我已经被封锁太久了。

Contains pre Java 8 code only.仅包含前 Java 8 代码。

public class ListFile {
    private static List<File> list = new ArrayList<>();

    private static void traverse(File path) {
        if (path.isFile()) {
            list.add(path);
        }
        else if (path.isDirectory()) {
            File[] files = path.listFiles();
            for (File f : files) {
                traverse(f);
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("ARGS: <directory>");
        }
        else {
            File path = new File(args[0]);
            traverse(path);
            Comparator<File> comp = new Comparator<File>() {
                
                @Override
                public int compare(File f1, File f2) {
                    if (f1 == null) {
                        if (f2 == null) {
                            return 0;
                        }
                        else {
                            return 1;
                        }
                    }
                    else {
                        if (f2 == null) {
                            return -1;
                        }
                        else {
                            Path p1 = f1.toPath();
                            Path p2 = f2.toPath();
                            try {
                                FileTime ft1 = (FileTime) Files.getAttribute(p1, "creationTime");
                                FileTime ft2 = (FileTime) Files.getAttribute(p2, "creationTime");
                                return ft1.compareTo(ft2);
                            }
                            catch (IOException xIo) {
                                throw new RuntimeException(xIo);
                            }
                        }
                    }
                }
            };
            Collections.sort(list, comp);
            int count = 0;
            int limit = 5;
            for (File f : list) {
                Path p = f.toPath();
                try {
                    FileTime ft = (FileTime) Files.getAttribute(p, "creationTime");
                    System.out.printf("[%s] %s%n", ft, p);
                }
                catch (IOException xIo) {
                    throw new RuntimeException(xIo);
                }
                if (++count == limit) {
                    break;
                }
            }
        }
    }
}

EDIT编辑

As requested, using NIO classes only.根据要求,仅使用 NIO 类。

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class ListFile {
    private static List<Path> lst = new ArrayList<>();

    private static void roam(Path path) throws IOException {
        if (Files.isRegularFile(path)) {
            lst.add(path);
        }
        else if (Files.isDirectory(path)) {
            DirectoryStream<Path> ds = Files.newDirectoryStream(path); // throws java.io.IOException
            Iterator<Path> iterator = ds.iterator();
            while (iterator.hasNext()) {
                roam(iterator.next());
            }
        }
    }

    /**
     * @param args - starting directory.
     *
     * @throws IOException  if fails to access directory.
     */
    public static void main(String[] args) throws IOException {
        if (args.length < 1) {
            System.out.println("ARGS: <directory>");
        }
        else {
            Path p = Paths.get(args[0]);
            roam(p);
            Comparator<Path> comp = new Comparator<Path>() {
                
                @Override
                public int compare(Path p1, Path p2) {
                    if (p1 == null) {
                        if (p2 == null) {
                            return 0;
                        }
                        else {
                            return 1;
                        }
                    }
                    else {
                        if (p2 == null) {
                            return -1;
                        }
                        else {
                            try {
                                FileTime ft1 = (FileTime) Files.getAttribute(p1, "creationTime");
                                FileTime ft2 = (FileTime) Files.getAttribute(p2, "creationTime");
                                return ft1.compareTo(ft2);
                            }
                            catch (IOException xIo) {
                                throw new RuntimeException(xIo);
                            }
                        }
                    }
                }
            };
            Collections.sort(lst, comp);
            int count = 0;
            int limit = 5;
            for (Path pth : lst) {
                try {
                    FileTime ft = (FileTime) Files.getAttribute(p, "creationTime");
                    System.out.printf("[%s] %s%n", ft, pth);
                }
                catch (IOException xIo) {
                    throw new RuntimeException(xIo);
                }
                if (++count == limit) {
                    break;
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我们如何使用 stream CSV 文件使用 Java NIO Api? - How we can stream a CSV file using Java NIO Api? 如何使用 Java NIO 将所有文件从源目录移动到目标目录,将现有文件保留在目标目录中? - How to move all files from source directory to destination directory, keeping existing files in destination directory, using Java NIO? 我可以使用Java按照创建日期检索文件吗? - can i retrieve files as per its creation date using java? 如何使用 Stream API 对列表进行排序? - How to sort a list of lists using the Stream API? 如何在java中的目录中对文件进行排序? - How can I sort files in a directory in java? 无法使用Files.walkFileTree在目录中打印子目录 - Can not print sub directory inside a directory using Files.walkFileTree java nio 我如何在Java驱动器中获取所有目录和文件列表。 (C:\\中的所有文件) - How can i get all the list of directories and files in a drive in java. (All files in C:\) 如何在 java 中不使用 sort() 方法对字符串进行排序? - How can i sort a string without using sort() method in java? Java 排序列表,然后使用 Stream api 从列表中获取子列表 - Java sort list and then take sublist from list using Stream api 将Google Drive API与Jav​​a配合使用,如何仅列出驱动器部分/文件夹中的文件 - Using Google Drive API with Java, how to list only files in the Drive Section/Folder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM