Before Java 8, you can use the listFiles() method of the File class with the parameter of the directory that we want to get the list of files and directories to do this. Eg:
1 |
File[] files = new File("/Users/khanh/Documents/code/huongdanjava.com").listFiles(); |
The return result will be a list of File objects containing information about the files and folders in the directory that we want to get the list. You can print the information of these files as follows:
1 2 3 |
for (File f: files) { System.out.println(f.getName()); } |
Result:
You can also filter out the list of files and folders if you want!
Another Java class that you can also use to get a list of files and directories is DirectoryStream.
But first, you need the Path object containing the directory information you need to get the list first:
1 2 |
String folder = "/Users/khanh/Documents/code/huongdanjava.com"; Path folderPath = Paths.get(folder); |
then use the DirectoryStream class as follows:
1 2 3 4 |
DirectoryStream<Path> ds = Files.newDirectoryStream(folderPath); for (Path path: ds) { System.out.println(path.getFileName()); } |
Result:
From Java 8 onwards, you can use the static list() method of the Files class to do this, specifically as follows:
1 2 3 4 5 6 7 8 |
String folder = "/Users/khanh/Documents/code/huongdanjava.com"; Path folderPath = Paths.get(folder); Files.list(folderPath) .map(Path::getFileName) .collect(Collectors.toList()) .stream() .forEach(System.out::println); |
The returned object of the list() method is a Stream object. You can get a list of names then collect them into a List, then for each List to print out the file name like I’m doing!
The result is the same as above: