DirectoryStream
Stay organized with collections
Save and categorize content based on your preferences.
Known Indirect Subclasses
SecureDirectoryStream<T> |
A DirectoryStream that defines operations on files that are located
relative to an open directory. |
|
An object to iterate over the entries in a directory. A directory stream
allows for the convenient use of the for-each construct to iterate over a
directory.
While DirectoryStream
extends Iterable
, it is not a
general-purpose Iterable
as it supports only a single Iterator
; invoking the iterator
method to obtain a second
or subsequent iterator throws IllegalStateException
.
An important property of the directory stream's Iterator
is that
its hasNext
method is guaranteed to read-ahead by
at least one element. If hasNext
method returns true
, and is
followed by a call to the next
method, it is guaranteed that the
next
method will not throw an exception due to an I/O error, or
because the stream has been closed
. The Iterator
does
not support the remove
operation.
A DirectoryStream
is opened upon creation and is closed by
invoking the close
method. Closing a directory stream releases any
resources associated with the stream. Failure to close the stream may result
in a resource leak. The try-with-resources statement provides a useful
construct to ensure that the stream is closed:
Path dir = ...
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path entry: stream) {
...
}
}
Once a directory stream is closed, then further access to the directory,
using the Iterator
, behaves as if the end of stream has been reached.
Due to read-ahead, the Iterator
may return one or more elements
after the directory stream has been closed. Once these buffered elements
have been read, then subsequent calls to the hasNext
method returns
false
, and subsequent calls to the next
method will throw
NoSuchElementException
.
A directory stream is not required to be asynchronously closeable.
If a thread is blocked on the directory stream's iterator reading from the
directory, and another thread invokes the close
method, then the
second thread may block until the read operation is complete.
If an I/O error is encountered when accessing the directory then it
causes the Iterator
's hasNext
or next
methods to
throw DirectoryIteratorException
with the IOException
as the
cause. As stated above, the hasNext
method is guaranteed to
read-ahead by at least one element. This means that if hasNext
method
returns true
, and is followed by a call to the next
method,
then it is guaranteed that the next
method will not fail with a
DirectoryIteratorException
.
The elements returned by the iterator are in no specific order. Some file
systems maintain special links to the directory itself and the directory's
parent directory. Entries representing these links are not returned by the
iterator.
The iterator is weakly consistent. It is thread safe but does not
freeze the directory while iterating, so it may (or may not) reflect updates
to the directory that occur after the DirectoryStream
is created.
Usage Examples:
Suppose we want a list of the source files in a directory. This example uses
both the for-each and try-with-resources constructs.
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;
}
Nested Class Summary
interface |
DirectoryStream.Filter<T> |
An interface that is implemented by objects that decide if a directory
entry should be accepted or filtered. |
Public Method Summary
abstract
Iterator<T>
|
iterator()
Returns the iterator associated with this DirectoryStream .
|
Inherited Method Summary
From interface
java.io.Closeable
abstract
void
|
close()
Closes this stream and releases any system resources associated
with it.
|
Public Methods
public
abstract
Iterator<T>
iterator
()
Returns the iterator associated with this DirectoryStream
.
Returns
- the iterator associated with this
DirectoryStream
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2024-07-10 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-07-10 UTC."],[[["\u003cp\u003e\u003ccode\u003eDirectoryStream\u003c/code\u003e provides an interface for iterating over entries within a directory, similar to using a for-each loop.\u003c/p\u003e\n"],["\u003cp\u003eIt is important to close the \u003ccode\u003eDirectoryStream\u003c/code\u003e using try-with-resources to prevent resource leaks.\u003c/p\u003e\n"],["\u003cp\u003eWhile extending \u003ccode\u003eIterable\u003c/code\u003e, \u003ccode\u003eDirectoryStream\u003c/code\u003e only supports a single \u003ccode\u003eIterator\u003c/code\u003e, and attempts to obtain additional iterators will result in an \u003ccode\u003eIllegalStateException\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eIterator\u003c/code\u003e's \u003ccode\u003ehasNext\u003c/code\u003e method reads ahead, guaranteeing the \u003ccode\u003enext\u003c/code\u003e method won't throw an I/O error if \u003ccode\u003ehasNext\u003c/code\u003e returns true.\u003c/p\u003e\n"],["\u003cp\u003eThe order of elements returned by the iterator is not guaranteed and may not reflect real-time updates to the directory due to its weak consistency.\u003c/p\u003e\n"]]],[],null,["public interface **DirectoryStream** implements [Closeable](../../../../reference/java/io/Closeable.html) [Iterable](../../../../reference/java/lang/Iterable.html)\\\u003cT\\\u003e \n\n|---|---|---|\n| Known Indirect Subclasses [SecureDirectoryStream](../../../../reference/java/nio/file/SecureDirectoryStream.html)\\\u003cT\\\u003e |----------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------| | [SecureDirectoryStream](../../../../reference/java/nio/file/SecureDirectoryStream.html)\\\u003cT\\\u003e | A `DirectoryStream` that defines operations on files that are located relative to an open directory. | |||\n\nAn object to iterate over the entries in a directory. A directory stream\nallows for the convenient use of the for-each construct to iterate over a\ndirectory.\n\n**While `DirectoryStream` extends `Iterable`, it is not a\ngeneral-purpose `Iterable` as it supports only a single `Iterator`; invoking the [iterator](../../../../reference/java/nio/file/DirectoryStream.html#iterator()) method to obtain a second\nor subsequent iterator throws `IllegalStateException`.**\n\nAn important property of the directory stream's `Iterator` is that\nits [hasNext](../../../../reference/java/util/Iterator.html#hasNext()) method is guaranteed to read-ahead by\nat least one element. If `hasNext` method returns `true`, and is\nfollowed by a call to the `next` method, it is guaranteed that the\n`next` method will not throw an exception due to an I/O error, or\nbecause the stream has been [closed](../../../../reference/java/io/Closeable.html#close()). The `Iterator` does\nnot support the [remove](../../../../reference/java/util/Iterator.html#remove()) operation.\n\nA `DirectoryStream` is opened upon creation and is closed by\ninvoking the `close` method. Closing a directory stream releases any\nresources associated with the stream. Failure to close the stream may result\nin a resource leak. The try-with-resources statement provides a useful\nconstruct to ensure that the stream is closed: \n\n```\n Path dir = ...\n try (DirectoryStream\u003cPath\u003e stream = Files.newDirectoryStream(dir)) {\n for (Path entry: stream) {\n ...\n }\n }\n \n```\n\nOnce a directory stream is closed, then further access to the directory,\nusing the `Iterator`, behaves as if the end of stream has been reached.\nDue to read-ahead, the `Iterator` may return one or more elements\nafter the directory stream has been closed. Once these buffered elements\nhave been read, then subsequent calls to the `hasNext` method returns\n`false`, and subsequent calls to the `next` method will throw\n`NoSuchElementException`.\n\nA directory stream is not required to be *asynchronously closeable* .\nIf a thread is blocked on the directory stream's iterator reading from the\ndirectory, and another thread invokes the `close` method, then the\nsecond thread may block until the read operation is complete.\n\nIf an I/O error is encountered when accessing the directory then it\ncauses the `Iterator`'s `hasNext` or `next` methods to\nthrow [DirectoryIteratorException](../../../../reference/java/nio/file/DirectoryIteratorException.html) with the [IOException](../../../../reference/java/io/IOException.html) as the\ncause. As stated above, the `hasNext` method is guaranteed to\nread-ahead by at least one element. This means that if `hasNext` method\nreturns `true`, and is followed by a call to the `next` method,\nthen it is guaranteed that the `next` method will not fail with a\n`DirectoryIteratorException`.\n\nThe elements returned by the iterator are in no specific order. Some file\nsystems maintain special links to the directory itself and the directory's\nparent directory. Entries representing these links are not returned by the\niterator.\n\nThe iterator is *weakly consistent* . It is thread safe but does not\nfreeze the directory while iterating, so it may (or may not) reflect updates\nto the directory that occur after the `DirectoryStream` is created.\n\n**Usage Examples:**\nSuppose we want a list of the source files in a directory. This example uses\nboth the for-each and try-with-resources constructs. \n\n```\n List\u003cPath\u003e listSourceFiles(Path dir) throws IOException {\n List\u003cPath\u003e result = new ArrayList\u003c\u003e();\n try (DirectoryStream\u003cPath\u003e stream = Files.newDirectoryStream(dir, \"*.{c,h,cpp,hpp,java}\")) {\n for (Path entry: stream) {\n result.add(entry);\n }\n } catch (DirectoryIteratorException ex) {\n // I/O error encounted during the iteration, the cause is an IOException\n throw ex.getCause();\n }\n return result;\n }\n \n```\n\n\u003cbr /\u003e\n\nSee Also\n\n- [Files.newDirectoryStream(Path)](../../../../reference/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path)) \n\nNested Class Summary\n\n|-----------|---|---|--------------------------------------------------------------------------------------------------------------|\n| interface | [DirectoryStream.Filter](../../../../reference/java/nio/file/DirectoryStream.Filter.html)\\\u003cT\\\u003e || An interface that is implemented by objects that decide if a directory entry should be accepted or filtered. |\n\nPublic Method Summary\n\n|-------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------|\n| abstract [Iterator](../../../../reference/java/util/Iterator.html)\\\u003cT\\\u003e | [iterator](../../../../reference/java/nio/file/DirectoryStream.html#iterator())() Returns the iterator associated with this `DirectoryStream`. |\n\nInherited Method Summary \nFrom interface [java.io.Closeable](../../../../reference/java/io/Closeable.html) \n\n|---------------|------------------------------------------------------------------------------------------------------------------------------------------|\n| abstract void | [close](../../../../reference/java/io/Closeable.html#close())() Closes this stream and releases any system resources associated with it. |\n\nFrom interface [java.lang.Iterable](../../../../reference/java/lang/Iterable.html) \n\n|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| void | [forEach](../../../../reference/java/lang/Iterable.html#forEach(java.util.function.Consumer\u003c?%20super%20T\u003e))([Consumer](../../../../reference/java/util/function/Consumer.html)\\\u003c? super T\\\u003e action) Performs the given action for each element of the `Iterable` until all elements have been processed or the action throws an exception. |\n| abstract [Iterator](../../../../reference/java/util/Iterator.html)\\\u003cT\\\u003e | [iterator](../../../../reference/java/lang/Iterable.html#iterator())() Returns an iterator over elements of type `T`. |\n| [Spliterator](../../../../reference/java/util/Spliterator.html)\\\u003cT\\\u003e | [spliterator](../../../../reference/java/lang/Iterable.html#spliterator())() Creates a [Spliterator](../../../../reference/java/util/Spliterator.html) over the elements described by this `Iterable`. |\n\nFrom interface [java.lang.AutoCloseable](../../../../reference/java/lang/AutoCloseable.html) \n\n|---------------|-------------------------------------------------------------------------------------------------------------------------------------|\n| abstract void | [close](../../../../reference/java/lang/AutoCloseable.html#close())() Closes this resource, relinquishing any underlying resources. |\n\nPublic Methods \n\npublic abstract [Iterator](../../../../reference/java/util/Iterator.html)\\\u003cT\\\u003e\n**iterator**\n() \nReturns the iterator associated with this `DirectoryStream`. \n\nReturns\n\n- the iterator associated with this `DirectoryStream` \n\nThrows\n\n| [IllegalStateException](../../../../reference/java/lang/IllegalStateException.html) | if this directory stream is closed or the iterator has already been returned |\n|-------------------------------------------------------------------------------------|------------------------------------------------------------------------------|"]]