Wrong Stream
You have an import for java.nio.stream.Stream
. But you need an import for java.util.stream.Stream
.
The Javadoc for Files.walk
tells us the method returns a java.util.stream.Stream<Path>
object.
import java.util.stream.Stream;
Closing I/O streams
By the way, that Stream
object implements AutoCloseable
. So you can use try-with-resources syntax to make sure it is closed properly, one way or another.
While closing some kinds of streams may be unnecessary, ones involving I/O should be closed. I assume this includes your Files.walk
stream.
To quote the Stream
interface Javadoc:
Most stream instances do not actually need to be closed after use, as they are backed by collections, arrays, or generating functions, which require no special resource management. Generally, only streams whose source is an IO channel, such as those returned by Files.lines(Path), will require closing. If a stream does require closing, it must be opened as a resource within a try-with-resources statement or similar control structure to ensure that it is closed promptly after its operations have completed.
Basic code sample
Path path = Paths.get( "/Users/basilbourque/stuff" );
try (
Stream < Path > subPaths = Files.walk( path ) ;
)
{
subPaths.forEach( System.out :: println );
}
catch ( IOException e )
{
e.printStackTrace();
}
Full sample code app
Here is a complete app, including the import
statements.
package work.basil.example;
import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Files;
import java.util.stream.Stream;
public class FileFinder
{
public void walkFiles ( )
{
Path path = Paths.get( "/Users/basilbourque/stuff" );
try (
Stream < Path > subPaths = Files.walk( path ) ;
)
{
subPaths.forEach( System.out :: println );
}
catch ( IOException e )
{
e.printStackTrace();
}
}
public static void main ( String[] args )
{
FileFinder app = new FileFinder();
app.demo();
}
private void demo ( )
{
this.walkFiles();
}
}
When run:
/Users/basilbourque/stuff
/Users/basilbourque/stuff/some_text.txt
/Users/basilbourque/stuff/slow-draft.txt
/Users/basilbourque/stuff/text.txt
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…