import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class LogFilter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String logFilePath = "";
String filterString = "";
// Get log file path from user
System.out.print("Enter log file path: ");
logFilePath = scanner.nextLine();
// Get filter string from user
System.out.print("Enter filter string: ");
filterString = scanner.nextLine();
try {
List<String> filteredLines = filterLogFile(logFilePath, filterString);
// Print filtered lines
if (filteredLines.isEmpty()) {
System.out.println("No matching lines found.");
} else {
for (String line : filteredLines) {
System.out.println(line);
}
}
} catch (IOException e) {
System.err.println("Error reading log file: " + e.getMessage());
} finally {
scanner.close();
}
}
/**
* Filters log file lines based on a given filter string.
* @param logFilePath The path to the log file.
* @param filterString The string to filter the log lines by.
* @return A list of filtered log lines.
* @throws IOException If an error occurs while reading the log file.
*/
public static List<String> filterLogFile(String logFilePath, String filterString) throws IOException {
List<String> filteredLines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(logFilePath))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(filterString)) {
filteredLines.add(line);
}
}
} catch (IOException e) {
throw e;
}
return filteredLines;
}
}
Add your comment