1. import java.io.IOException;
  2. import java.nio.file.Files;
  3. import java.nio.file.Path;
  4. import java.nio.file.Paths;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9. public class LogSearch {
  10. /**
  11. * Searches log files for a given pattern.
  12. * @param filePath The path to the log file.
  13. * @param searchPattern The regular expression pattern to search for.
  14. * @return A list of lines containing the search pattern. Returns an empty list if no match or error.
  15. * @throws IOException If an I/O error occurs while reading the file.
  16. */
  17. public List<String> searchLogFile(String filePath, String searchPattern) throws IOException {
  18. List<String> results = new ArrayList<>();
  19. // Defensive check: Validate input
  20. if (filePath == null || filePath.trim().isEmpty()) {
  21. System.err.println("Error: File path cannot be null or empty.");
  22. return results; // Return empty list
  23. }
  24. if (searchPattern == null || searchPattern.trim().isEmpty()) {
  25. System.err.println("Error: Search pattern cannot be null or empty.");
  26. return results; // Return empty list
  27. }
  28. Path path = Paths.get(filePath);
  29. try {
  30. String fileContent = new String(Files.readAllBytes(path));
  31. Pattern pattern = Pattern.compile(searchPattern);
  32. Matcher matcher = pattern.matcher(fileContent);
  33. while (matcher.find()) {
  34. results.add(fileContent.substring(matcher.start(), matcher.end())); // Extract matching line
  35. }
  36. } catch (IOException e) {
  37. System.err.println("Error reading file: " + e.getMessage());
  38. return results; // Return empty list
  39. }
  40. return results;
  41. }
  42. public static void main(String[] args) throws IOException {
  43. LogSearch searcher = new LogSearch();
  44. // Example usage:
  45. String filePath = "example.log"; // Replace with your log file path
  46. String searchPattern = "ERROR"; // Replace with your search pattern
  47. //Create a dummy log file for testing
  48. try {
  49. Files.write(Paths.get(filePath), "This is a log line.\n".getBytes());
  50. Files.write(Paths.get(filePath), "Another log line.\n".getBytes());
  51. Files.write(Paths.get(filePath), "ERROR: Something went wrong.\n".getBytes());
  52. Files.write(Paths.get(filePath), "Just a normal line.\n".getBytes());
  53. Files.write(Paths.get(filePath), "ERROR: Another error occurred.\n".getBytes());
  54. } catch (IOException e) {
  55. System.err.println("Error creating dummy log file: " + e.getMessage());
  56. return;
  57. }
  58. List<String> results = searcher.searchLogFile(filePath, searchPattern);
  59. if (results.isEmpty()) {
  60. System.out.println("No matches found.");
  61. } else {
  62. System.out.println("Matches found:");
  63. for (String line : results) {
  64. System.out.println(line);
  65. }
  66. }
  67. }
  68. }

Add your comment