javajava-streamsupplier

Still getting "stream has already been operated upon or closed" error


I'm reading lines from a txt file trying to get two lines at once (current and next). I use Supplier, but still get the error.

Stream<String> lines = Files.lines(Paths.get(fileName));
Supplier<Stream<String>> streamSupplier = () -> lines;
Optional<String> line = streamSupplier.get().skip(offset).findFirst();
Optional<String> nextLine = streamSupplier.get().skip(offset+1).findFirst();

What am I missing here?


Solution

  • The problem is that your supplier isn't giving you two instances of the stream: it's giving you the same one each time. streamSupplier.get() is no different from using lines directly.

    If you want to read two things from the stream, skip by offset, then limit by 2, then collect to a list:

    List<String> items = lines.skip(offset).limit(2).collect(Collectors.toList());
    

    Now you can get those items from the list:

    Optional<String> line = items.size() > 0 ? Optional.of(items.get(0)) : Optional.empty();
    Optional<String> nextLine = items.size() > 1 ? Optional.of(items.get(1)) : Optional.empty();