List files in a directory in Java
List files in a directory in Java
List files using File.listFiles()
You can use File.listFiles() method to list files in a directory. listFiles method can take a FileFilter as an argument and returns an array of files.
1 | File file = new File("/path/to/directory"); |
List files using Files.walk()
Also, you can use Files.walk() method to list files in a directory. Files.walk() method returns a Stream
1 | Path path = Paths.get("/path/to/directory"); |
List files in classpath
If you want to list files in the classpath, you can use the following code snippet:
1 | URL url = this.getClass().getClassLoader().getResource("directory"); |
If you are using Spring, you can use ResourceUtils class to get the file from the classpath:
1 | File file = ResourceUtils.getFile("classpath:directory"); |