In Java, Files.list(dir) returns a Stream<Path> of the files and folders directly insidedir. It is not recursive: the contents of subfolders are not included, and the special entries . and .. never appear.
Entries come in no particular order, so sort them if order matters. The stream keeps the directory open, so close it with try-with-resources.
A static method of the final utility class java.nio.file.Files, available since Java 8. Call it on the class name, as in Files.list(...), after import java.nio.file.Files;. You never create a Files object.
Run with java ListDirectChildren. Directory order is unspecified, so the program sorts the names before printing; the output is the same on Windows, macOS, and Linux.
Three children. The temp folder holds two files and the docs folder; docs/inner.txt is one level further down.
Names, then sort. Each Path is reduced to its file name and sorted, because the system may return entries in any order.
Not recursive. inner.txt is missing from the list; use walk to include it.
Example 2 — Separate Files from Folders
Filter with Files::isRegularFile for files, then open a second stream to count folders.
Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListFilesOnly {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Files.write(dir.resolve("todo.txt"), new byte[0]);
Files.write(dir.resolve("notes.txt"), new byte[0]);
Files.createDirectory(dir.resolve("img"));
Files.createDirectory(dir.resolve("music"));
List<String> files;
try (Stream<Path> entries = Files.list(dir)) {
files = entries.filter(Files::isRegularFile)
.map(p -> p.getFileName().toString())
.sorted()
.collect(Collectors.toList());
}
long folders;
try (Stream<Path> entries = Files.list(dir)) {
folders = entries.filter(Files::isDirectory).count();
}
System.out.println("Files: " + files);
System.out.println("Folders: " + folders);
for (String name : new String[] {"todo.txt", "notes.txt", "img", "music"}) {
Files.delete(dir.resolve(name));
}
Files.delete(dir);
}
}
Output
Run with java ListFilesOnly. Directory order is unspecified, so the program sorts the names before printing; the output is the same on Windows, macOS, and Linux.
Files: [notes.txt, todo.txt]
Folders: 2
How It Works
Method reference as filter.Files::isRegularFile keeps only ordinary files and drops img and music.
One stream, one pass. A stream cannot be reused, so counting folders opens a fresh Files.list.
Sorted names, plain count. notes.txt sorts before todo.txt; a count needs no sorting because it does not depend on order.
Example 3 — An Empty Folder, a File, and a Missing Path
An empty folder gives an empty stream; a file or a missing path throws when list is called.