140 likes | 248 Views
File Input / Output. Files. Persistent storage So your application can ‘remember’ Similar methods to reading / displaying information as before, but a different ‘destination’. Scanner Class. Before, we read data from ‘standard input’ Scanner myScanner = new Scanner (System.in);
E N D
Files • Persistent storage • So your application can ‘remember’ • Similar methods to reading / displaying information as before, but a different ‘destination’
Scanner Class • Before, 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 Class • Now we use the FileReader class • Don’t forget your imports • java.util • java.io • Scanner myScanner = new Scanner (new FileReader(“c:\\myfolder\\myFile.txt”);
FileReader • Scanner 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 slashes • Slash is the escape character • Paths • Relative vs. Absolute • Drive letters
FileReader • Now we can use the same scanner methods • nextInt( ) • nextDouble( ) • hasNext( )
Example Scanner 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 file • print( ) • 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
Exceptions • For 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 hold • Products • Comments • Reviews