Avatar ·

How to read all files from a folder in Java? (recursively and non-recursively)

Hello everyone! I just started learning Java and came across this task: I need to write a program that reads all files from a specific directory. For example, I have a folder "data" with text files of different sizes, and I want to get their contents as strings. I tried to do it myself, but it's not working out yet.\n\nHere's what I wrote:\n\n
import java.io.File;\nimport java.io.FileReader;\nimport java.io.BufferedReader;\n\npublic class ReadFiles {\n    public static void main(String[] args) {\n        File folder = new File("data");\n        File[] listOfFiles = folder.listFiles();\n        \n        for (File file : listOfFiles) {\n            if (file.isFile()) {\n                BufferedReader reader = new BufferedReader(new FileReader(file));\n                String li