File Input / Output
FilesPersistent storage
So your application can ‘remember’
Similar methods to reading / displaying information as before, but a different ‘destination’
Scanner ClassBefore, we read data from ‘standard input’
Scanner myScanner = new Scanner (System.in);
System.in will read from the keyboard
We can pass Scanner other Objects to read from other sources…
Scanner ClassNow we use the FileReader class
Don’t forget your importsjava.utiljava.io
Scanner myScanner = new Scanner (new FileReader(“c:\\myfolder\\myFile.txt”);
FileReaderScanner myScanner = new Scanner (new FileReader(“c:\\myfolder\\myFile.txt”);
Some Things to notice:
We create a FileReader Object “on the fly” It doesn’t even have a name
The double slashesSlash is the escape character
PathsRelative vs. AbsoluteDrive letters
FileReaderNow we can use the same scanner
methodsnextInt( )nextDouble( )hasNext( )
ExampleScanner myScanner = new Scanner (new FileReader(“c:\\myFile.txt”));
String firstName, lastName;
double hoursWorked, payRate, wages;
firstName = myScanner.next( );
lastName = myScanner.next( );
hoursWorked = myScanner.nextDouble( );
payRate = myScanner.nextDouble( );
wages = hoursWorked * payRate;
myScanner.close( );
Writing to Files
Lots of different “Writer and Reader” classes.
PrintWriter is a good, high level class for reading general data from a file
Writing to Files
PrintWriter myPW = new PrintWriter(“c:\\myFile.out”);
Can use the familiar output methods on the fileprint( )println( )
myPW.println(“The pay is: $” + pay);This stores the text in the file “myFile.out”
Closing Files
Don’t forget to close your files!
Saves memory and…
“Flushes the buffer”
Files
What happens if something goes wrong?
Trying to read a file that isn’t there…
Trying to write to a location that doesn’t exist…Like the ‘Z:’ drive
Trying to write to a file that is already there…By default, it overwrites the file.This may not be what you want!
Files
If something goes wrong, the statement that causes a problem throws an exception
One of two things must happen in a method that causes an exception
You deal with it
Or… pass the problem up to the calling method
ExceptionsFor now, we will ‘pass the buck’ and let the
system deal with the potential error
public static void main (String [] args) throws FileNotFoundException {
. . .
// no try – catch block in here
}
Files
In the real-world, files are useful, but many real world data tasks are handled via a database
mySQL
Websites use a database to holdProductsCommentsReviews