import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
public class LogCompactor {
public static void compactLog(String logFilePath, long timeoutMillis) throws IOException, TimeoutException {
// Read all lines from the log file
List<String> lines = readAllLines(logFilePath);
if (lines == null || lines.isEmpty()) {
System.out.println("Log file is empty.");
return;
}
// Compact the log - output only the last 'n' lines (e.g., last 100)
int numLinesToKeep = Math.min(100, lines.size()); //Keep last 100 lines or all lines if less than 100
List<String> compactedLines = lines.subList(lines.size() - numLinesToKeep, lines.size());
// Write the compacted lines to a new file
writeLinesToFile(compactedLines, "compacted_" + logFilePath);
System.out.println("Log file compacted to: compacted_" + logFilePath);
}
private static List<String> readAllLines(String filePath) throws IOException {
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
return lines;
}
private static void writeLinesToFile(List<String> lines, String filePath) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (String line : lines) {
writer.write(line);
writer.newLine();
}
}
}
public static void main(String[] args) throws IOException, TimeoutException {
//Example usage
String logFile = "test.log"; // Replace with your log file path
long timeout = 5000; // Timeout in milliseconds
//Create a dummy log file for testing
try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile))) {
for (int i = 0; i < 200; i++) {
writer.write("Log line " + (i + 1) + "\n");
}
}
try {
compactLog(logFile, timeout);
} catch (IOException | TimeoutException e) {
System.err.println("Error compacting log file: " + e.getMessage());
e.printStackTrace();
}
}
}
Add your comment