1. import java.io.File;
  2. import java.io.IOException;
  3. class FileHandler {
  4. /**
  5. * Processes a file and handles potential file-related exceptions.
  6. * @param filePath The path to the file.
  7. * @return True if the file was processed successfully, false otherwise.
  8. */
  9. public boolean processFile(String filePath) {
  10. File file = new File(filePath);
  11. try {
  12. // Check if the file exists
  13. if (!file.exists()) {
  14. System.err.println("Error: File not found: " + filePath);
  15. return false; // Indicate failure
  16. }
  17. // Check if the file is a regular file
  18. if (!file.isFile()) {
  19. System.err.println("Error: Not a file: " + filePath);
  20. return false;
  21. }
  22. // Attempt to read the file (example operation)
  23. String content = readFileContent(filePath);
  24. System.out.println("File content: " + content); //Example successful operation
  25. return true; // Indicate success
  26. } catch (IOException e) {
  27. System.err.println("Error processing file " + filePath + ": " + e.getMessage());
  28. e.printStackTrace(); // Print stack trace for debugging
  29. return false; // Indicate failure
  30. }
  31. }
  32. /**
  33. * Reads the content of a file.
  34. * @param filePath The path to the file.
  35. * @return The content of the file, or null if an error occurred.
  36. * @throws IOException if an I/O error occurs.
  37. */
  38. private String readFileContent(String filePath) throws IOException {
  39. java.io.FileReader reader = new java.io.FileReader(filePath);
  40. try (java.io.BufferedReader br = new java.io.BufferedReader(reader)) {
  41. StringBuilder sb = new StringBuilder();
  42. String line;
  43. while ((line = br.readLine()) != null) {
  44. sb.append(line).append(System.lineSeparator());
  45. }
  46. return sb.toString();
  47. }
  48. }
  49. public static void main(String[] args) {
  50. FileHandler handler = new FileHandler();
  51. // Example usage:
  52. String validFilePath = "test.txt"; //replace with an existing file
  53. String invalidFilePath = "nonexistent_file.txt"; //replace with a non-existing file
  54. //Create test file if it doesn't exist
  55. File testFile = new File(validFilePath);
  56. try{
  57. testFile.createNewFile();
  58. } catch(IOException e){
  59. System.err.println("Error creating test file: " + e.getMessage());
  60. }
  61. handler.processFile(validFilePath);
  62. handler.processFile(invalidFilePath);
  63. }
  64. }

Add your comment