1. import java.io.File;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8. public class FileContentSearch {
  9. /**
  10. * Searches files for a given hypothesis and optional flags.
  11. *
  12. * @param directoryPath The directory to search in.
  13. * @param hypothesis The hypothesis to search for.
  14. * @param flags Optional flags to include in the search. Can be null or empty.
  15. * @return A list of file paths where the hypothesis was found.
  16. */
  17. public static List<String> searchFiles(String directoryPath, String hypothesis, String flags) {
  18. List<String> results = new ArrayList<>();
  19. if (directoryPath == null || directoryPath.isEmpty() || hypothesis == null || hypothesis.isEmpty()) {
  20. return results; // Return empty list for invalid input
  21. }
  22. File directory = new File(directoryPath);
  23. if (!directory.exists() || !directory.isDirectory()) {
  24. System.err.println("Invalid directory path: " + directoryPath);
  25. return results;
  26. }
  27. Pattern pattern;
  28. if (flags != null && !flags.isEmpty()) {
  29. pattern = Pattern.compile("(" + flags + ")");
  30. } else {
  31. pattern = Pattern.compile(hypothesis);
  32. }
  33. try {
  34. Files.walkFileLocations(directory.toPath())
  35. .filter(file -> file.isFile()) // Only process files
  36. .forEach(file -> {
  37. try {
  38. String content = new String(Files.readAllBytes(file));
  39. Matcher matcher = pattern.matcher(content);
  40. if (matcher.find()) {
  41. results.add(file.toPath().toString());
  42. }
  43. } catch (IOException e) {
  44. System.err.println("Error reading file " + file.toPath() + ": " + e.getMessage());
  45. }
  46. });
  47. } catch (IOException e) {
  48. System.err.println("Error walking directory " + directoryPath + ": " + e.getMessage());
  49. }
  50. return results;
  51. }
  52. public static void main(String[] args) {
  53. // Example Usage
  54. String directory = "test_files"; // Replace with your directory
  55. String hypothesis = "example";
  56. String flags = "flag1,flag2";
  57. List<String> foundFiles = searchFiles(directory, hypothesis, flags);
  58. if (foundFiles.isEmpty()) {
  59. System.out.println("No files found containing '" + hypothesis + "' and flags '" + flags + "'.");
  60. } else {
  61. System.out.println("Files containing '" + hypothesis + "' and flags '" + flags + "':");
  62. for (String file : foundFiles) {
  63. System.out.println(file);
  64. }
  65. }
  66. }
  67. }

Add your comment