java - list files and directories from directory

Java
[Edit]
+
0
-
0

Java - list files and directories from directory

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import java.io.File; import java.io.IOException; public class Program { public static void main(String[] args) throws IOException { File directory = new File("C:\\path\\to\\directory"); String[] names = directory.list(); // contains names of files and directories if (names != null) { for (String name : names) { System.out.println(name); } } } }
[Edit]
+
0
-
0

Java - list files and directories from directory

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// import java.nio.file.Files; // import java.nio.file.Paths; var directoryPath = Paths.get("/path/to/directory"); try (var directoryStream = Files.newDirectoryStream(directoryPath)) { for (var entryPath : directoryStream) { if (Files.isDirectory(entryPath) || Files.isRegularFile(entryPath)) { var fileName = entryPath.getFileName(); // ... } } } // Note: to find more optimal version go to https://dirask.com/snippets/Java-list-files-and-directories-from-directory-pYPmND
[Edit]
+
0
-
0

Java - list files and directories from directory

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// import java.nio.file.Files; // import java.nio.file.Paths; // import java.nio.file.attribute.BasicFileAttributes; var directoryPath = Paths.get("/path/to/directory"); try (var directoryStream = Files.newDirectoryStream(directoryPath)) { for (var entryPath : directoryStream) { var fileSystem = entryPath.getFileSystem(); var systemProvider = fileSystem.provider(); var fileAttributes = systemProvider.readAttributes(entryPath, BasicFileAttributes.class); if (fileAttributes.isDirectory() || fileAttributes.isRegularFile()) { var entryName = entryPath.getFileName(); // ... } } } // Note: this example reduces number of access to file system provider.