0

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);

                }
        }

        }
  • Possible duplicate of [How to search for a string from a file in java?](https://stackoverflow.com/questions/3905100/how-to-search-for-a-string-from-a-file-in-java) – Chris K Jun 10 '19 at 17:03
  • You ask about reading files, but you show code writing files? Why is that? – GhostCat Jun 10 '19 at 17:09
  • So please read [mcve] and enhance your question accordingly. – GhostCat Jun 10 '19 at 17:10
  • Possible duplicate of [Java - Read file and split into multiple files](https://stackoverflow.com/questions/19177994/java-read-file-and-split-into-multiple-files) – Joao Vitorino Jun 10 '19 at 17:45

1 Answers1

1

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.

J. Lengel
  • 570
  • 3
  • 16