Dan*_*her 38 java nio file directorystream
我想列出指定目录中的所有FILES和该目录中的子目录.不应列出任何目录.
我目前的代码如下.它无法正常工作,因为它只列出指定目录中的文件和目录.
我怎样才能解决这个问题?
final List<Path> files = new ArrayList<>();
Path path = Paths.get("C:\\Users\\Danny\\Documents\\workspace\\Test\\bin\\SomeFiles");
try
{
DirectoryStream<Path> stream;
stream = Files.newDirectoryStream(path);
for (Path entry : stream)
{
files.add(entry);
}
stream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
for (Path entry: files)
{
System.out.println(entry.toString());
}
Run Code Online (Sandbox Code Playgroud)
问候.
Vla*_*ich 63
Java 8为此提供了一个很好的方法:
Files.walk(path)
Run Code Online (Sandbox Code Playgroud)
此方法返回Stream<Path>.
Evg*_*eev 31
如果下一个元素是目录,请创建一个调用自身的方法
void listFiles(Path path) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
listFiles(entry);
}
files.add(entry);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Adi*_*Adi 26
检查FileVisitor,非常整洁.
Path path= Paths.get("C:\\Users\\Danny\\Documents\\workspace\\Test\\bin\\SomeFiles");
final List<Path> files=new ArrayList<>();
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if(!attrs.isDirectory()){
files.add(file);
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
如果你想避免函数以递归方式调用自身并拥有一个成员变量的文件列表,你可以使用一个堆栈:
private List<Path> listFiles(Path path) throws IOException {
Deque<Path> stack = new ArrayDeque<Path>();
final List<Path> files = new LinkedList<>();
stack.push(path);
while (!stack.isEmpty()) {
DirectoryStream<Path> stream = Files.newDirectoryStream(stack.pop());
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
stack.push(entry);
}
else {
files.add(entry);
}
}
stream.close();
}
return files;
}
Run Code Online (Sandbox Code Playgroud)