Skip to content

How to get file name having particular content in it using java?

Here I am trying to read a folder containing .sql files and I am getting those files in an array, now my requirement is to read every file and find particular word like as join if join is present in the file return filename or else discard , someone can pls help me with this ..

import java.io.File;
import java.io.IOException;
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.Optional;
import java.util.stream.Stream;

public class Filter {

    public static List<String> textFiles(String directory) {
        List<String> textFiles = new ArrayList<String>();
        File dir = new File(directory);
        for (File file : dir.listFiles()) {
            if (file.getName().endsWith((".sql"))) {
                textFiles.add(file.getName());
            }
        }
        return textFiles;

    }

    public static void getfilename(String directory) throws IOException {
        List<String> textFiles = textFiles(directory);
        for (String string : textFiles) {
            Path path = Paths.get(string);
            try (Stream<String> streamOfLines = Files.lines(path)) {
                Optional<String> line = streamOfLines.filter(l -> l.contains("join")).findFirst();
                if (line.isPresent()) {
                    System.out.println(path.getFileName());
                } else
                    System.out.println("Not found");
            } catch (Exception e) {
            }

        }
    }

    public static void main(String[] args) throws IOException {
        getfilename("/home/niteshb/wave1-master/wave1/sql/scripts");
    }
}

Answer

You can search word in file as belwo, pass the path of file

try(Stream <String> streamOfLines = Files.lines(path)) {
  Optional <String> line = streamOfLines.filter(l -> 
                       l.contains(searchTerm))
                       .findFirst();
  if(line.isPresent()){
   System.out.println(line.get()); // you can add return true or false   
  }else
   System.out.println("Not found");
}catch(Exception e) {}

}