70 likes | 155 Views
Reading Data From A File. The Scanner class can read input from a keyboard. Ex: Scanner keyboard = new Scanner(System.in);. “System.in” tells the scanner object to read from the keyboard. “keyboard” is the name of the scanner object. The Scanner class can also read input from a file.
E N D
The Scanner class can read input from a keyboard. • Ex: Scanner keyboard = new Scanner(System.in); “System.in” tells the scanner object to read from the keyboard. “keyboard” is the name of the scanner object.
The Scanner class can also read input from a file. • Instead of using “System.in”, you can reference a file oject. • Ex: File myFile = new File(“MisterCrow.txt”); Scanner inputFile = new Scanner(myFile); Creating a file object. “inputFile” is the name of the Scanner object. Now the scanner can read from a file!
This example reads the first line from the file: //Open the file File file = new File(“Crow.txt”); Scanner inputfile = new Scanner(file); //Read the first line from the file strLine = inputFile.nextLine(); //Display the line System.out.println(strLine);
hasNext( ) method: • To read the rest of the file, you must be able to detect the end of a file. Otherwise, the program will crash. • You can use the hasNext( ) method to detect the end of a file. • The hasNext( ) method is usually used with a loop. If it has reached the end of a file, it will return a value of false. It there is another line of text in the file, it will return a value of true.
Ex: //Open the file File file = new File(“Crow.txt”); Scanner inputFile = new Scanner(file); //Read lines from the file until there are no more left while (inputFile.hasNext( ) ) { //Read the next name strInput = inputFile.nextLine( ); //Display the text that was read System.out.println(strInput); } inputFile.close( );
Also, keep in mind that you must use the “throws clause” when dealing with input and output. • Always have the following written in your method header: Public static void main(String[ ] args) throws IOException { }