1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.Scanner;
  7. public class LogFilter {
  8. public static void main(String[] args) {
  9. Scanner scanner = new Scanner(System.in);
  10. String logFilePath = "";
  11. String filterString = "";
  12. // Get log file path from user
  13. System.out.print("Enter log file path: ");
  14. logFilePath = scanner.nextLine();
  15. // Get filter string from user
  16. System.out.print("Enter filter string: ");
  17. filterString = scanner.nextLine();
  18. try {
  19. List<String> filteredLines = filterLogFile(logFilePath, filterString);
  20. // Print filtered lines
  21. if (filteredLines.isEmpty()) {
  22. System.out.println("No matching lines found.");
  23. } else {
  24. for (String line : filteredLines) {
  25. System.out.println(line);
  26. }
  27. }
  28. } catch (IOException e) {
  29. System.err.println("Error reading log file: " + e.getMessage());
  30. } finally {
  31. scanner.close();
  32. }
  33. }
  34. /**
  35. * Filters log file lines based on a given filter string.
  36. * @param logFilePath The path to the log file.
  37. * @param filterString The string to filter the log lines by.
  38. * @return A list of filtered log lines.
  39. * @throws IOException If an error occurs while reading the log file.
  40. */
  41. public static List<String> filterLogFile(String logFilePath, String filterString) throws IOException {
  42. List<String> filteredLines = new ArrayList<>();
  43. try (BufferedReader reader = new BufferedReader(new FileReader(logFilePath))) {
  44. String line;
  45. while ((line = reader.readLine()) != null) {
  46. if (line.contains(filterString)) {
  47. filteredLines.add(line);
  48. }
  49. }
  50. } catch (IOException e) {
  51. throw e;
  52. }
  53. return filteredLines;
  54. }
  55. }

Add your comment