To read all files from a folder in Java, you can use the java.io.File
class or the java.nio.file.Files
class. Here’s an example using Files
class in Java 8:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class ReadFilesFromFolderExample { public static void main(String[] args) { String folderPath = "path/to/folder"; try { List<Path> files = Files.list(Paths.get(folderPath)).filter(Files::isRegularFile).toList(); for (Path file : files) { System.out.println(file.getFileName()); } } catch (IOException e) { e.printStackTrace(); } } }
Using Regular Files
File folder = new File("path/to/folder/"); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.isFile()) { System.out.println(file.getName()); } }