2

How to read data from all the files (one-by-one) in a folder with Java?

this code simply returns names of files, I'm looking for an even deeper search:

File folder = new File("/home/user_name/Downloads/textfiles/");
File[] listOfFiles = folder.listFiles();

for (File file : listOfFiles) {
    if (file.isFile()) {
        System.out.println(file.getName());
    }
}
user10274438
  • 123
  • 1
  • 2
  • 10

3 Answers3

6

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("————————————————————————————————");
        });
    }
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • Thanks. This works Precisely!! – user10274438 Sep 18 '18 at 08:50
  • I didn't understand this part. Map> linesOfFiles = new TreeMap>();` – user10274438 Sep 18 '18 at 09:15
  • `Map`s are data structures that store values that belong to a key. In this case, the key is the file name and the corresponding values are a list of lines. Both, file name and lines are `String`s, that's why the `map` is structured as `Map`. This is basically storing pairs of file name and the content of that file. You can read more about that in the [tutorial about the Map interface](https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html). – deHaar Sep 18 '18 at 09:22
1

The standard Java 8 way is simply to iterate all Paths in the given directory:

Path inputDir = Paths.get("path/to/dir");
if (Files.isDirectory(inputDir)) {
    List<Path> filePaths = Files.list(inputDir).collect(Collectors.toList());
    for (Path filePath : filePaths) {
        // Load file contents...
    }
}

What you put in the loop depends on your needs. You could make a Reader, stream the lines out or even memory-map it depending on how much memory you want to use and on performance requirements etc.

Paul Benn
  • 1,911
  • 11
  • 26
0

using commons-io

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>


public static void main(String[] args) {
    try {
        File files = new File("\\home\\folder");
        for (File file : files.listFiles()) {
            List<String> lines = FileUtils.readLines(file);
            System.out.println();
            System.out.println();
            System.out.println("******" + file.getName());
            for (String line : lines) {
                System.out.println(line);
            }
            System.out.println(file.getName() + "******");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Gnk
  • 645
  • 4
  • 11