Reading textual data from a file is very similar in many ways to reading input from the keyboard. The Scanner
class and all of its methods remain the same. However, you must also import the classes java.io.File
and java.io.IOException
. Also, the way in which you use the Scanner
class constructor changes.
The java.io.File
is a holder class that can take a String
representing the path to a file on your computer. Creating a Scanner
object that reads from a file is as simple as:
Scanner in = new Scanner(new File(“test.txt”));
File f = new File(“C:\MyDocuments\Java\tester.txt”);
Scanner in2 = new Scanner(f);
Scanner will take no responsibility in handling the exception, so every time that you want to use Scanner with a file, you will have to use a try-catch block. A full example is shown below:
Scanner in;
try{
in = new Scanner(new File("test.txt"));
String test = in.nextLine();
System.out.println(test);
}catch(IOException i){
System.out.println("Error: " + i.getMessage());
}
When reading a large amount of data from a file, it is often useful to know whether there is any more data in the file to read.
NoSuchElementException
and stop your program. The Scanner
class has several methods for determining if there is any more data in the file to be read: hasNext()
, hasNextDouble()
, and hasNextInt(
will be the methods most useful for you. hasNext()
will return true, while hasNextDouble()
will return true only if a valid double is next and hasNextInt()
will return true only if an int value is next. Using a simple while loop, you can easily read in data until the end of a file.while(in.hasNext()){
System.out.println(in.next());
}
Last modified: December 12, 2022
Back to Throwing Exceptions