user11506860
user11506860

Reputation:

How to read files content in Folder

How do you read file content on a folder, iam saying like that i want to return all the files on a folder that contains a specific word! Here is a method that return all the files with a specific exe But now i want to read the content behind all the files

File [] files= folder.listFiles((File f) -> f.getName().endsWith(ext) && f.length() / 1024 < kb);


            FileWriter fw = new FileWriter("C://Users//Admin//Desktop//foldtest123");
            BufferedWriter bw = new BufferedWriter(fw);
        try (PrintWriter pw = new PrintWriter(bw)) {
            pw.println("Ne folderin : " + folder.getName() + " keto fajlla kane plotesuar kushtin");
                for (File files1: files) {
                        pw.println(fajllat1);

                }
        }

        }

Upvotes: 0

Views: 51

Answers (1)

J. Lengel
J. Lengel

Reputation: 588

You can do this the same way (using a lambda):

File[] files = folder.listFiles(f -> {
    try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
        String line;

        while ((line = reader.readLine() + '\n' /*very important!!!*/) != null) {
            if (line.contains(PATTERN)) return true;
        }
    } catch (IOException e) {
        // error
    }

    return false;
});

This is quite slow since you possibly have to read through each file just to get an array of files which you can write to later but it is the only way of achieving that.

Upvotes: 1

Related Questions