1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. public class FilePerformance {
  5. public static void main(String[] args) {
  6. // Example usage: Replace with your file path
  7. String filePath = "test.txt";
  8. long startTime = System.currentTimeMillis();
  9. long fileSize = getFileSize(filePath);
  10. long endTime = System.currentTimeMillis();
  11. System.out.println("File size: " + fileSize + " bytes");
  12. System.out.println("Time to get file size: " + (endTime - startTime) + " ms");
  13. startTime = System.currentTimeMillis();
  14. try {
  15. readWholeFile(filePath);
  16. } catch (IOException e) {
  17. System.err.println("Error reading file: " + e.getMessage());
  18. }
  19. endTime = System.currentTimeMillis();
  20. System.out.println("Time to read whole file: " + (endTime - startTime) + " ms");
  21. }
  22. private static long getFileSize(String filePath) throws IOException {
  23. File file = new File(filePath);
  24. return file.length();
  25. }
  26. private static void readWholeFile(String filePath) throws IOException {
  27. FileInputStream fileInputStream = null;
  28. try {
  29. fileInputStream = new FileInputStream(filePath);
  30. byte[] fileContent = fileInputStream.readAllBytes(); // Read entire file content
  31. // Process fileContent here (e.g., analyze, validate)
  32. // For this example, we just read it.
  33. } finally {
  34. if (fileInputStream != null) {
  35. fileInputStream.close(); // Ensure file stream is closed
  36. }
  37. }
  38. }
  39. }

Add your comment