When the main method of this class executes, this output is created:
java.io.FileNotFoundException: demo.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at fileio.main(Demo.java:4).
because there is no catch() block to trap the FileNotFoundException,
which then propagates up to the JVM, which finally traps it and displays the
stack trace.
Solution:
public class Demo { public static void main(String[] args) { try { FileInputStream iStream = new FileInputStream("demo.txt"); } catch (NullPointerException e){ System.out.println(“Can’t open file for input”) } catch (FileNotFoundException e){ // an extra catch block is needed to catch FileNotFoundExceotion System.out.println(“Can’t open file for input”); } } }
![]() | Opens the text file whose name is supplied as the argument. The text file contains an arbitrary number of integer values (one per line), but may also contain invalid values (non-numeric). |
![]() | Creates an ArrayList that can contain integers. |
![]() | Reads each line of the text file, and for valid integer values, adds the value to the ArrayList. When invalid values are encountered because of NumberFormatExceptions, they are simply ignored. |
![]() | The method should propagate no exceptions, and close the file before
returning. Solution: public List Reading the following file: 1 2 3 abc 4 def 6 76 8 9 produces the following
output: Value read: 1 Value read: 2 Value read: 3 Ignoring abc Value read: 4 Ignoring def Value read: 6 Value read: 76 Value read: 8 Value read: 9 Closing file! |