List directory content with Project Reactor and DirectoryStream

后端 未结 2 1034
礼貌的吻别
礼貌的吻别 2021-01-26 15:00

I\'d like to use DirectoryStream with Project Reactor to list all the files in a directory.

My try is:

Path myDir = Paths.get(\"C:\\\\Users\\\\r.dacanal\         


        
相关标签:
2条回答
  • 2021-01-26 15:35

    list(dir) on directories with large amount of files uses too much memory, there is a reason for newDirectoryStream

    0 讨论(0)
  • 2021-01-26 15:43

    Subscribe repeatedly calls iterator(), but DirectoryStream has a check to ensure that the iterator must be null before assigning it's own

    @Override
    public Iterator<Path> iterator() {
        if (!isOpen) {
            throw new IllegalStateException("Directory stream is closed");
        }
        synchronized (this) {
            if (iterator != null)
                throw new IllegalStateException("Iterator already obtained");
            iterator = new WindowsDirectoryIterator(firstName);
            return iterator;
        }
    }
    

    Although if you are using Java 8+ there is 0 reason to be using newDirectoryStream(dir) as you can use list(dir) to provide an actual Stream

    The following should work

    Path myDir = Paths.get("C:\\Users\\r.dacanal\\Documents\\Reply\\EDA\\logging-consumer\\input");
    Stream<Path> directoryStream = Files.list(myDir);
    Flux.fromStream(directoryStream).doOnNext(System.out::println).subscribe();
    
    0 讨论(0)
提交回复
热议问题