Yes.
import java.util.Scanner; import java.io.*; public class EchoSquareDisk { public static void main (String[] args) throws IOException { File file = new File("myData.txt"); // create a File object Scanner scan = new Scanner( file ); // connect a Scanner to the file int num, square; num = scan.nextInt(); square = num * num ; System.out.println("The square of " + num + " is " + square); scan.close(); } }
This program reads its data from
myData.txt
, a text file.
The first line of the file contains an integer in character format, such as:
12
There can be spaces before or after the 12. The
Scanner
scans over spaces until
it finds characters that can be converted to int
.
It stops scanning when it encounters the first space after the digits.
Any additional characters in the file are ignored.
If the file myData.txt does not exist in the current disk directory,
or if there are other problems opening it,
the Scanner
constructor will throw an IOException
.
Because of this the main()
method must declare
throws IOException
An Exception
object contains data about what went wrong and can be used for
dealing with the problem.
This program merely passes the Exception
to the runtime system.
This is called throwing the Exception
.
Is it possible that the file myData.txt
might not exist?