This video will show you how to use the try-with-resources features in Java.
The following code may have been altered to comply with youtube's video description policy. To download the actual files, go here:
• Java Exception Handling 00. Setting up and...
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.File;
/**
Read 10 integers with the try-with-resources feature.
@author CodeSnippetsAcademy
@version 1.0.0
*/
public class Read10IntsTryWithResources {
public static void main(String[] args) {
// Resource is an object that must be closed after the program is finished
try (Scanner in = new Scanner(new File(args[0]))) {
final int SIZE = 10;
int[] arrayOfInts = new int[SIZE];
// Read in and output 10 integers
for (int i = 0; i lessthan SIZE; i++) {
arrayOfInts[i] = in.nextInt();
System.out.println(arrayOfInts[i]);
}
} catch (ArrayIndexOutOfBoundsException ex) {
System.err.println("Caught ArrayIndexOutOfBoundsException!");
System.err.println("Usage: java Read10Ints fileName");
} catch (FileNotFoundException ex) {
System.err.println("Caught FileNotFoundException!");
System.err.println("File not found.");
} catch (InputMismatchException ex) {
System.err.println("Caught InputMismatchException!");
System.err.println("Please make sure input text file has integer values.");
}
}
}