1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.TimeoutException;
  7. public class FilePathRestorer {
  8. /**
  9. * Restores file paths from a file with a timeout.
  10. * @param filePath The path to the file containing file paths.
  11. * @param maxTimeMs The maximum time to wait for reading the file (in milliseconds).
  12. * @return A list of file paths, or an empty list if an error occurs or the file is empty.
  13. * @throws IOException if an I/O error occurs while reading the file.
  14. * @throws TimeoutException if the file reading operation exceeds the timeout.
  15. */
  16. public static List<String> restoreFilePaths(String filePath, long maxTimeMs) throws IOException, TimeoutException {
  17. List<String> filePaths = new ArrayList<>();
  18. try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  19. long startTime = System.currentTimeMillis();
  20. String line;
  21. while ((line = reader.readLine()) != null) {
  22. if (System.currentTimeMillis() - startTime > maxTimeMs) {
  23. throw new TimeoutException("File reading timed out.");
  24. }
  25. filePaths.add(line.trim()); // Add file path, removing leading/trailing whitespace
  26. }
  27. } catch (IOException e) {
  28. throw e; // Re-throw the IOException
  29. }
  30. return filePaths;
  31. }
  32. public static void main(String[] args) {
  33. // Example usage:
  34. String filePath = "file_paths.txt"; // Replace with your file path
  35. long timeout = 5000; // Timeout in milliseconds
  36. try {
  37. List<String> restoredPaths = restoreFilePaths(filePath, timeout);
  38. for (String path : restoredPaths) {
  39. System.out.println(path);
  40. }
  41. } catch (IOException | TimeoutException e) {
  42. System.err.println("Error restoring file paths: " + e.getMessage());
  43. }
  44. }
  45. }

Add your comment