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.regex.Matcher;
import java.util.regex.Pattern;
public class LogSearch {
/**
* Searches log files for a given pattern.
* @param filePath The path to the log file.
* @param searchPattern The regular expression pattern to search for.
* @return A list of lines containing the search pattern. Returns an empty list if no match or error.
* @throws IOException If an I/O error occurs while reading the file.
*/
public List<String> searchLogFile(String filePath, String searchPattern) throws IOException {
List<String> results = new ArrayList<>();
// Defensive check: Validate input
if (filePath == null || filePath.trim().isEmpty()) {
System.err.println("Error: File path cannot be null or empty.");
return results; // Return empty list
}
if (searchPattern == null || searchPattern.trim().isEmpty()) {
System.err.println("Error: Search pattern cannot be null or empty.");
return results; // Return empty list
}
Path path = Paths.get(filePath);
try {
String fileContent = new String(Files.readAllBytes(path));
Pattern pattern = Pattern.compile(searchPattern);
Matcher matcher = pattern.matcher(fileContent);
while (matcher.find()) {
results.add(fileContent.substring(matcher.start(), matcher.end())); // Extract matching line
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
return results; // Return empty list
}
return results;
}
public static void main(String[] args) throws IOException {
LogSearch searcher = new LogSearch();
// Example usage:
String filePath = "example.log"; // Replace with your log file path
String searchPattern = "ERROR"; // Replace with your search pattern
//Create a dummy log file for testing
try {
Files.write(Paths.get(filePath), "This is a log line.\n".getBytes());
Files.write(Paths.get(filePath), "Another log line.\n".getBytes());
Files.write(Paths.get(filePath), "ERROR: Something went wrong.\n".getBytes());
Files.write(Paths.get(filePath), "Just a normal line.\n".getBytes());
Files.write(Paths.get(filePath), "ERROR: Another error occurred.\n".getBytes());
} catch (IOException e) {
System.err.println("Error creating dummy log file: " + e.getMessage());
return;
}
List<String> results = searcher.searchLogFile(filePath, searchPattern);
if (results.isEmpty()) {
System.out.println("No matches found.");
} else {
System.out.println("Matches found:");
for (String line : results) {
System.out.println(line);
}
}
}
}
Add your comment