1. import java.io.*;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.concurrent.TimeoutException;
  5. public class LogCompactor {
  6. public static void compactLog(String logFilePath, long timeoutMillis) throws IOException, TimeoutException {
  7. // Read all lines from the log file
  8. List<String> lines = readAllLines(logFilePath);
  9. if (lines == null || lines.isEmpty()) {
  10. System.out.println("Log file is empty.");
  11. return;
  12. }
  13. // Compact the log - output only the last 'n' lines (e.g., last 100)
  14. int numLinesToKeep = Math.min(100, lines.size()); //Keep last 100 lines or all lines if less than 100
  15. List<String> compactedLines = lines.subList(lines.size() - numLinesToKeep, lines.size());
  16. // Write the compacted lines to a new file
  17. writeLinesToFile(compactedLines, "compacted_" + logFilePath);
  18. System.out.println("Log file compacted to: compacted_" + logFilePath);
  19. }
  20. private static List<String> readAllLines(String filePath) throws IOException {
  21. List<String> lines = new ArrayList<>();
  22. try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  23. String line;
  24. while ((line = reader.readLine()) != null) {
  25. lines.add(line);
  26. }
  27. }
  28. return lines;
  29. }
  30. private static void writeLinesToFile(List<String> lines, String filePath) throws IOException {
  31. try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
  32. for (String line : lines) {
  33. writer.write(line);
  34. writer.newLine();
  35. }
  36. }
  37. }
  38. public static void main(String[] args) throws IOException, TimeoutException {
  39. //Example usage
  40. String logFile = "test.log"; // Replace with your log file path
  41. long timeout = 5000; // Timeout in milliseconds
  42. //Create a dummy log file for testing
  43. try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile))) {
  44. for (int i = 0; i < 200; i++) {
  45. writer.write("Log line " + (i + 1) + "\n");
  46. }
  47. }
  48. try {
  49. compactLog(logFile, timeout);
  50. } catch (IOException | TimeoutException e) {
  51. System.err.println("Error compacting log file: " + e.getMessage());
  52. e.printStackTrace();
  53. }
  54. }
  55. }

Add your comment