Upload
vutram
View
222
Download
0
Embed Size (px)
Citation preview
Chapter 9 2
Announcements
• Project 5 due last night• Project 6 assigned• Exam 2
– Wed., March 21, 7:00 – 8:00 pm, LILY 1105– Chapters 5–9
• Discussion group after Spring Break– Monday, B155, 7:00 – 9:00pm– Exam review!
3
File I/OWhy bother? Persistent storage
Use over multiple sessions Safety In case of failure (program,
computer)
What are files? Collections of bytes
Can be abstracted and viewed otherwise Different Types?
4
Streams All file I/O is treated like a stream
Moving flow of data Different classes can work with the stream
– Provide filters and abstractions– Like an assembly line for data
File
FileInputStream
Lots of data
DataInputStreambytes
int
char
boolean
doubleString
5
Streams
A stream can only flow in one direction. Need input streams and output streams
Useful classes:
GeneralFileString (split)JFileChooser
InputFileInputStreamDataInputStreamObjectInputStreamFileReaderBufferedReaderScanner
OutputFileOutputStreamDataOutputStreamObjectOutputStream(FileWriter)PrintWriter
Chapter 9 6
Text Files and Binary Files
• All data in a file is stored as binary digits.– Files with contents that must be treated as
sequences of binary digits are called binary files; binary files can be read only by machines.
Chapter 9 7
Text Files and Binary Files,cont.
• Sometimes, it is more convenient to think of a file’s contents as a sequence of characters.– Files with streams and methods to make
them look like sequences of characters are called text files; text files can be read by people.
Chapter 9 8
Text Files and Binary Files, cont.
• However, binary files are more efficient to process than text files.
• In Java, binary files are platform- independent.– Binary files can be created by one
computer and read by another, combining portability and efficiency.
Chapter 9 9
Text Files and Binary Files, cont.
• Though text files can be read and written using an editor, binary files must be read and written by a program.
10
Example 1What does the following program do?
try {String in = "in.txt";int numLines = 5;BufferedReader reader =
new BufferedReader( new FileReader( in ) );
for ( int line = 0; line < numLines; ++line ) {System.out.println( reader.readLine() );
}
} catch( IOException ioe ) {System.err.println( "Crush! Kill! Destroy!" );
}
What if the number of lines is unknown?Is there anything missing?
11
Example 2try {
String in = "in.txt";BufferedReader reader = new BufferedReader( new FileReader( in ) );String line = reader.readLine();while( null != line ) {
System.out.println( reader.readLine() );line = reader.readLine();
}} catch( IOException ioe ) {
System.err.println( "I can't do that, Dave!" );}
But we still need to close it!Where?
What changes when reading a byte at a time?
12
Example 3BufferedReader reader = null;try { ...} catch( IOException ioe ){ ...
} finally { try {
if ( null != reader ) reader.close();
} catch( IOException ioe ) {System.err.println( "Error closing file" );
}}
close() should almost alwaysbe called in a finally block!
13
Scanner Classimport java.util.Scanner;import java.io.File;import java.io.FileNotFoundException;...
try {Scanner scanner =
new Scanner( new File( “in.txt” ) );
while( scanner.hasNextLine() ) {System.out.println( scanner.nextLine() );
}
} catch( FileNotFoundException e ) {System.err.println( "Unable to open file!" );
}
Chapter 9 14
Use toString for Text-File Output
• Classes typically include a method toString.• The methods println and print in class
PrintWriter behave like System.out.println and System.out.print, respectively.
15
Example - toString()
PrintWriter writer = null;
try {
String outFile = "out.txt";
writer =
new PrintWriter(new FileOutputStream(outFile));
Date today = new Date();
writer.println( today.toString() );
writer.println( "Today is " + today );
} catch( FileNotFoundException ioe ) {
System.err.println( "Exterrrrrrminate!" );
} finally {...}
Notice: toString() is part of any object
Chapter 9 16
StringTokenizer Class
• Class BufferedReader can read entire lines or single characters, but not single words.
• Class StringTokenizer can take an entire line of text and break it into individual words.
• The class StringTokenizer is in the java.util package.
• Individual words are called tokens.
Chapter 9 17
StringTokenizer example• Tokens are nonwhitespace characters.
StringTokenizer tokenizer =
new StringTokenizer(“Read my lips!”)
while (tokenizer.hasMoreTokens()) {
System.out.println( tokenizer.nextToken() );
}
producesRead
my
lips!
Chapter 9 18
StringTokenizer, cont'd
• Separators are whitespace characters unless otherwise specified.
• To specify a set of separators, a string consisting of all the separator characters is given as a second argument to the constructor.
• example… new StringTokenizer(“Read my lips!”, “\n.,!”);
Chapter 9 19
String.split() example• StringTokenizer is a legacy class!
– use String split() methodString s = “Read my lips!”
String[] tokens = s.split( “ “ );
for( String token : tokens ) {
System.out.println( token );
}
producesRead
my
lips!
split() argument is the delimeter
Chapter 9 20
Using the File Class
• The methods of the class File can check the properties of files.– Does the named file exist?– Is the file readable?
• Typically, the operating systems lets you designate files as not readable or as readable only by certain users.
Chapter 9 21
Using the File Class, cont.
• The File class is like a wrapper class for strings which are file names.– example
new File(“treasure.txt”)
Chapter 9 22
Some File Methods public boolean exists()
public boolean canRead()
public boolean canWrite()
public boolean delete()
public boolean length()
public String getName()
public String getPath()
Can these be used to avoid exceptions?
23
Object I/OObject I/O can be binary ObjectInputStream and ObjectOutputStream
ObjectOutputStream oos = new ObjectOutputStream
new FileOutputStream( <filename> ) );oos.writeObject( new Date() );...ObjectInputStream ois = new ObjectInputStream
new FileInputStream( <filename> ) );Date aDate = (Date)ois.readObject();
Chapter 9 25
The EOFException Class
• ObjectInputStream methods that read from a binary file throw an EOFException when they try to read beyond the end of the file.
• When using class ObjectInputStream, the class EOFException can test for the end of a file.
Chapter 9 27
Checking for the End of File
• Different classes with file reading methods check for the end of a file in different ways.– Binary files throw an exception in the class EOFException.
– A text file returns a special value, such as null.
• Be sure to test for the end of the file in the correct way.
28
Object Stream Concerns
Could an instance of the following class be written: public class SomeClass {
String aString = “someText”;
}
Why or why not?
29
Object Stream Concerns
Any object serialized by a stream must implement Serializable - Acts as a marker for what can be written
public class SomeClass implements Serializable
{
String aString = “someText”;
}
Chapter 9 30
The Serializable Interface
• A class which is serializable affects how Java performs file I/O with objects of the class.– Java assigns a serial number to each
object of the class that it writes to a stream of type ObjectOutputStream.
– If the object is written more than once, Java writes only the serial number for the object.
Chapter 9 31
Array Objects in Binary Files
• An entire array can be saved to a binary file using objectWrite, and can be read later using objectRead.
• If the base type of the array is a class, the class should be serializable.
• All the data in an array can be outputted to a binary file using a single invocation of objectWrite.
Chapter 9 32
(optional) Graphics Supplement
• Programming Example: A JFrame GUI for Manipulating Files– Accept a file and display its first line.– Provide an explanatory message if the file
does not exist or is unreadable.– Delete a selected file.– Provide an explanatory message if the file
does not exist or is unwriteable (and hence cannot be deleted).