Java How to list all files in a directory?
By:Roy.LiuLast updated:2019-08-11
Two Java examples to show you how to list files in a directory :
- For Java 8, Files.walk
- Before Java 8, create a recursive loop to list all files.
1. Files.walk
1.1 List all files.
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.filter(Files::isRegularFile) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace();
1.2 List all folders.
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.filter(Files::isDirectory) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace();
1.3 List all files end with .java
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.map(x -> x.toString()) .filter(f -> f.endsWith(".java")).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace();
1.4 Find a file – HeaderAnalyzer.java
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.map(x -> x.toString()) .filter(f -> f.contains("HeaderAnalyzer.java")) .collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace();
2. Classic
In the old days, we can create a recursive loop to implement the search file function like this :
2.1 List all files end with .java
package com.mkyong.example; import java.io.File; import java.util.ArrayList; import java.util.List; public class JavaExample { public static void main(String[] args) { final File folder = new File("C:\\projects"); List<String> result = new ArrayList<>(); search(".*\\.java", folder, result); for (String s : result) { System.out.println(s); public static void search(final String pattern, final File folder, List<String> result) { for (final File f : folder.listFiles()) { if (f.isDirectory()) { search(pattern, f, result); if (f.isFile()) { if (f.getName().matches(pattern)) { result.add(f.getAbsolutePath());
References
From:一号门
Previous:Java How to run Windows bat file
COMMENTS