Why is Files.lines (and similar Streams) not automatically closed?

前端 未结 4 1485
再見小時候
再見小時候 2020-11-27 16:23

The javadoc for Stream states:

Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually n

4条回答
  •  长情又很酷
    2020-11-27 17:05

    If you're lazy like me and don't mind the "if an exception is raised, it will leave the file handle open" you could wrap the stream in an autoclosing stream, something like this (there may be other ways):

      static Stream allLinesCloseAtEnd(String filename) throws IOException {
        Stream lines = Files.lines(Paths.get(filename));
        Iterator linesIter = lines.iterator();
    
        Iterator it = new Iterator() {
          @Override
          public boolean hasNext() {
            if (!linesIter.hasNext()) {
              lines.close(); // auto-close when reach end
              return false;
            }
            return true;
          }
    
          @Override
          public Object next() {
            return linesIter.next();
          }
        };
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT), false);
      }
    

提交回复
热议问题