import java.io.File;
import java.io.IOException;
class FileHandler {
/**
* Processes a file and handles potential file-related exceptions.
* @param filePath The path to the file.
* @return True if the file was processed successfully, false otherwise.
*/
public boolean processFile(String filePath) {
File file = new File(filePath);
try {
// Check if the file exists
if (!file.exists()) {
System.err.println("Error: File not found: " + filePath);
return false; // Indicate failure
}
// Check if the file is a regular file
if (!file.isFile()) {
System.err.println("Error: Not a file: " + filePath);
return false;
}
// Attempt to read the file (example operation)
String content = readFileContent(filePath);
System.out.println("File content: " + content); //Example successful operation
return true; // Indicate success
} catch (IOException e) {
System.err.println("Error processing file " + filePath + ": " + e.getMessage());
e.printStackTrace(); // Print stack trace for debugging
return false; // Indicate failure
}
}
/**
* Reads the content of a file.
* @param filePath The path to the file.
* @return The content of the file, or null if an error occurred.
* @throws IOException if an I/O error occurs.
*/
private String readFileContent(String filePath) throws IOException {
java.io.FileReader reader = new java.io.FileReader(filePath);
try (java.io.BufferedReader br = new java.io.BufferedReader(reader)) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append(System.lineSeparator());
}
return sb.toString();
}
}
public static void main(String[] args) {
FileHandler handler = new FileHandler();
// Example usage:
String validFilePath = "test.txt"; //replace with an existing file
String invalidFilePath = "nonexistent_file.txt"; //replace with a non-existing file
//Create test file if it doesn't exist
File testFile = new File(validFilePath);
try{
testFile.createNewFile();
} catch(IOException e){
System.err.println("Error creating test file: " + e.getMessage());
}
handler.processFile(validFilePath);
handler.processFile(invalidFilePath);
}
}
Add your comment