You could do it without any external library, just with java.nio.
The procedure is as follows:
The code takes a path as String
and creates a java.nio.Path
out of it (done with a constant String
path in this example). Then it prepares a Map<String, List<Strings>
that is to store the file name and its content as one String
per line. After that, it reads the directory content using the DirectoryStream<Path>
from java.nio into a list of file paths and stores both, the content read by Files.readAllLines(Path path)
as a List<String>
and the absolute file path in the Map
.
Finally, it just prints out everything read, separated by a line of long dashes...
Just try it, maybe it is helpful for your search.
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class FileContentReader {
private static final String FOLDER_PATH = "Y:\\our\\destination\\folder\\";
public static void main(String[] args) {
Path folderPath = Paths.get(FOLDER_PATH);
// prepare a data structure for a file's name and content
Map<String, List<String>> linesOfFiles = new TreeMap<String, List<String>>();
// retrieve a list of the files in the folder
List<String> fileNames = new ArrayList<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(folderPath)) {
for (Path path : directoryStream) {
fileNames.add(path.toString());
}
} catch (IOException ex) {
System.err.println("Error reading files");
ex.printStackTrace();
}
// go through the list of files
for (String file : fileNames) {
try {
// put the file's name and its content into the data structure
List<String> lines = Files.readAllLines(folderPath.resolve(file));
linesOfFiles.put(file, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
// finally, print everything
linesOfFiles.forEach((String fileName, List<String> lines) -> {
System.out.println("Content of " + fileName + " is:");
lines.forEach((String line) -> {
System.out.println(line);
});
System.out.println("————————————————————————————————");
});
}
}