fsharpsquare fsharpsquare - 17 days ago 6
Java Question

Print all content from multiple files in directory

I have the following code seen below, this code looks through a directory and then prints all of the different file names. Now my question is, how would I go about changing my code, so that it would also print out all of the content within the files which it finds/prints? As an example, lets say the code finds 3 files in the directory, then it would print out all the content within those 3 files.

import java.io.File;
import java.io.IOException;

public class EScan {


static String usernamePc = System.getProperty("user.name");
final static File foldersPc = new File("/Users/" + usernamePc + "/Library/Mail/V2");

public static void main(String[] args) throws IOException {

listFilesForFolder(foldersPc);

}

public static void listFilesForFolder(final File foldersPc) throws IOException {
for (final File fileEntry : foldersPc.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}

}

Answer

You may use Scanner to read the contents of the file

try {
        Scanner sc = new Scanner(fileEntry);

        while (sc.hasNextLine()) {
            String s = sc.nextLine();
            System.out.println(s);
        }

        sc.close();
    } catch (Exception e) {
        e.printStackTrace();
}