Resource leak in Files.list(Path dir) when stream is not explicitly closed?

后端 未结 3 1161
广开言路
广开言路 2020-12-15 03:51

I recently wrote a small app that periodically checked the content of a directory. After a while, the app crashed because of too many open file handles. After some debugging

3条回答
  •  悲&欢浪女
    2020-12-15 04:27

       List fileList = null;
    
       try (Stream list = Files.list(Paths.get(path.toString()))) {
       fileList = 
         list.filter(Files::isRegularFile).map(Path::toFile).map(File::getAbsolutePath)
                                    .collect(Collectors.toList());
       } catch (IOException e) {
        logger.error("Error occurred while reading email files: ", e);
      }
    

提交回复
热议问题