import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileReader { public static void main(String[] args) { try { File myFile = new File("file.txt"); Scanner scanner = new Scanner(myFile); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } scanner.close(); } catch (FileNotFoundException e) { System.out.println("The file does not exist or cannot be found."); e.printStackTrace(); } } }
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class BinaryFileReader { public static void main(String[] args) { try { FileInputStream inputStream = new FileInputStream("binaryfile.bin"); int i; while ((i = inputStream.read()) != -1) { System.out.print((char) i); } inputStream.close(); } catch (FileNotFoundException e) { System.out.println("The file does not exist or cannot be found."); e.printStackTrace(); } catch (IOException e) { System.out.println("Error reading from file: " + e.getMessage()); e.printStackTrace(); } } }In this example, we are reading from a binary file using a FileInputStream object. If the file cannot be found, a FileNotFoundException is thrown and caught in the try-catch block. If an IO error occurs while reading from the file, an IOException is thrown and caught. The program then prints an error message and the stack trace for the exception. Both of these examples use classes from the java.io package, which is a built-in library in Java for handling input and output operations.