1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. import java.time.Duration;
  5. import java.time.LocalDateTime;
  6. import java.util.Scanner;
  7. public class LogFilePerformance {
  8. public static void main(String[] args) {
  9. Scanner scanner = new Scanner(System.in);
  10. System.out.println("Log File Performance Measurement Tool");
  11. String logFilePath = promptForLogFilePath(scanner);
  12. long fileSize = getFileSize(logFilePath);
  13. long startTime = System.currentTimeMillis();
  14. long linesRead = countLines(logFilePath);
  15. long endTime = System.currentTimeMillis();
  16. long duration = endTime - startTime;
  17. double linesPerSecond = (double) linesRead / (duration / 1000);
  18. System.out.println("\n--- Performance Results ---");
  19. System.out.println("Log File: " + logFilePath);
  20. System.out.println("File Size: " + fileSize + " bytes");
  21. System.out.println("Lines Read: " + linesRead);
  22. System.out.println("Time Taken: " + Duration.ofMillis(duration) + " ms");
  23. System.out.println("Lines per Second: " + String.format("%.2f", linesPerSecond) + " lines/s");
  24. scanner.close();
  25. }
  26. private static String promptForLogFilePath(Scanner scanner) {
  27. System.out.print("Enter the path to the log file: ");
  28. return scanner.nextLine();
  29. }
  30. private static long getFileSize(String filePath) {
  31. try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  32. long fileSize = 0;
  33. long bufferSize = 1024;
  34. byte[] buffer = new byte[bufferSize];
  35. int bytesRead;
  36. while ((bytesRead = reader.read(buffer)) != -1) {
  37. fileSize += bytesRead;
  38. }
  39. return fileSize;
  40. } catch (IOException e) {
  41. System.err.println("Error getting file size: " + e.getMessage());
  42. return -1; // Indicate an error.
  43. }
  44. }
  45. private static long countLines(String filePath) {
  46. try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  47. long lineCount = 0;
  48. String line;
  49. while ((line = reader.readLine()) != null) {
  50. lineCount++;
  51. }
  52. return lineCount;
  53. } catch (IOException e) {
  54. System.err.println("Error counting lines: " + e.getMessage());
  55. return -1; // Indicate an error.
  56. }
  57. }
  58. }

Add your comment