7
Reading Data From A File

Reading Data From A File

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: Reading Data From A File

Reading Data From A File

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

Page 3: Reading Data From A File

• 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);

Now the scanner can read from a file!

“inputFile” is the name of the Scanner object.

Creating a file object.

Page 4: Reading Data From A File

• This example reads the first line from the file:

//Open the fileFile file = new File(“Crow.txt”);Scanner inputfile = new Scanner(file);

//Read the first line from the filestrLine = inputFile.nextLine();

//Display the lineSystem.out.println(strLine);

Page 5: Reading Data From A File

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

Page 6: Reading Data From A File

• Ex://Open the fileFile file = new File(“Crow.txt”);Scanner inputFile = new Scanner(file);

//Read lines from the file until there are no more leftwhile (inputFile.hasNext( ) ){

//Read the next namestrInput = inputFile.nextLine( );

//Display the text that was readSystem.out.println(strInput);

}

inputFile.close( );

Page 7: Reading Data From A File

• 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

{

}