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);
The first line assumes that there is a file named “test.txt” in the directory or folder where you run your java files. The second line shows an example of creating the File object in its own line of code. It also shows the File being created with the full path to the file. This would be used if your text file was not in the same directory as your Java files. But what happens if the file that you are looking for doesn’t exist or has some other status that prevents it from being read? This causes an exception to be thrown!
- 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. Reading from a file which has no more data will give you a
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 ¡ will be the methods most useful for you. If there is anything still to come, 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());
}