繁体   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();
        }
    }
}

如果不使用 Stream 并仅使用 NIO 按创建日期对其进行排序,我该如何做到这一点?

首先,我需要检查是否存在特定文件。 第二个 function 是按创建日期对所有文件进行排序。

我认为我应该返回一组文件和创建日期,然后对其进行排序。

您只需将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());

我不认为您可以从文件 api 中找到创建日期。

此示例使用FileVisitor工作。 它比 stream 示例长,但在非常大的目录结构上会更快,因为FileVisitor提供了 BasicFileAttributes,因此避免了文件 IO 调用排序。

另外,您可以按名称、创建、修改时间等进行排序:

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;
    }
}

我想你可以看出我已经被封锁太久了。

仅包含前 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;
                }
            }
        }
    }
}

编辑

根据要求,仅使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM