T - 迭代器返回的元素的类型 
       public interface DirectoryStream<T> extends Closeable, Iterable<T>
 虽然DirectoryStream扩展了Iterable ,但它不是通用的Iterable ,因为它只支持一个Iterator ; 调用iterator方法获得第二个或后续的迭代器抛出IllegalStateException 。 
 目录流Iterator一个重要属性是它的hasNext方法被保证通过至少一个元素预读。 如果hasNext方法返回true ,之后是调用next方法,则保证next方法不会因I / O错误而引发异常,或者因为流已经是closed 。 Iterator不支持remove操作。 
 A DirectoryStream在创建时打开,并通过调用close方法关闭。 关闭目录流将释放与流相关联的任何资源。 未能关闭流可能会导致资源泄漏。 try-with-resources语句提供了一个有用的结构,以确保流被关闭: 
  Path dir = ...
   try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
       for (Path entry: stream) {
           ...
       }
   }  
        一旦目录流关闭,则使用Iterator进一步访问Iterator行为就像流已经达到一样。 由于预读, Iterator可能会在目录流关闭后返回一个或多个元素。 一旦这些缓冲元素被读取,那么对hasNext方法的后续调用将返回false ,并且后续调用next方法将抛出NoSuchElementException 。 
 目录流不需要异步关闭 。 如果从目录中读取的目录流的迭代器中阻塞一个线程,另一个线程调用close方法,则第二个线程可能会阻塞,直到读取操作完成。 
 如果在访问目录时遇到I / O错误,则导致Iterator的hasNext或next方法以IOException作为原因丢弃DirectoryIteratorException 。 如上所述, hasNext方法保证通过至少一个元素预读。 这意味着如果hasNext方法返回true ,并且后跟一个调用next方法,那么保证next方法不会与DirectoryIteratorException失败。 
迭代器返回的元素没有特定的顺序。 某些文件系统维护目录本身和目录的父目录的特殊链接。 代表这些链接的条目不会由迭代器返回。
 迭代器弱一致 。 它是线程安全的,但在迭代时不冻结目录,因此它可能(或可能不)反映在创建DirectoryStream之后发生的DirectoryStream更新。 
使用示例:假设我们想要一个目录中的源文件的列表。 此示例同时使用for-each和try-with-resources构造。
  List<Path> listSourceFiles(Path dir) throws IOException {
       List<Path> result = new ArrayList<>();
       try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) {
           for (Path entry: stream) {
               result.add(entry);
           }
       } catch (DirectoryIteratorException ex) {
           // I/O error encounted during the iteration, the cause is an IOException
           throw ex.getCause();
       }
       return result;
   }  
      Files.newDirectoryStream(Path) 
       | Modifier and Type | Interface and Description | 
|---|---|
| static interface  | DirectoryStream.Filter<T>
              由对象执行的接口,用于确定是否应接受或过滤目录条目。 
             | 
 Submit a bug or feature 
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved.