1 / 7

Reading Data From A File

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.

Download Presentation

Reading Data From A File

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Reading Data From A File

  2. 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.

  3. 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!

  4. 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);

  5. 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.

  6. 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( );

  7. 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 { }

More Related