Powerpoint Slides

Download Report

Transcript Powerpoint Slides

Streams and File I/O
Chapter 9
Chapter 9
1
Reminders
• Project 6 released: due Nov 03 @ 10:30 pm
• Project 4 regrades due by midnight tonight
• Discussion groups now twice a week (7-9
pm: M in CS G066, W in Phys 11)
Chapter 9
2
Exam 2
•
•
•
•
Tuesday, October 25
7:00 – 8:00 PM
Physics 112
Covers chapters 5-9 (and material from 1-4
as well)
• Similar format as Exam 1
– 20 MC
– 4 programming
Chapter 9
3
Why Use Files for I/O?
• Keyboard input and screen output deal only
with temporary data, which is lost when the
program ends.
• Files permit data to be stored permanently (or
at least until a program changes the file).
• Input files can be used over and over by
different programs.
• Files also provide convenient storage and
retrieval of large quantities of data.
Chapter 9
4
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
5
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
6
Text Files and Binary Files,
cont.
• However, all files are binary in the computer
– Just a sequence of 0s and 1s: it’s how we
(or programs) interpret those 0s and 1s
Chapter 9
7
Text File Output Example
Chapter 9
8
Use toString for Output
Chapter 9
9
Text File Input Example
Chapter 9
10
The StringTokenizer
Class, cont.
• Tokens are nonwhitespace characters.
• example
StringTokenizer tokenizer = new
StringTokenizer(“Read my lips!”)
while (tokenizer.hasMoreTokens())
{
System.out.println
(tokenizer.nextToken());
}
Chapter 9
11
The StringTokenizer
Class, cont.
• This will produce
Read
my
lips!
Chapter 9
12
The StringTokenizer
Class, cont.
• 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
13
Some Methods in Class
StringTokenizer
• constructors
public StringTokenizer(String
theString)
public StringTokenizer(String
theString, String delimiters)
• more tokens?
public boolean hasMoreTokens()
• next token
public String nextToken()
• remaining tokens
public int countTokens()
Chapter 9
14
Example: StringTokenizer
• Display the words separated by any of the following
characters: space, new line (\n), period (.) or comma (,).
String inputLine = keyboard.nextLine();
StringTokenizer wordFinder =
new StringTokenizer(inputLine, " \n.,");
while(wordFinder.hasMoreTokens())
{
System.out.println(wordFinder.nextToken());
}
Chapter 9
15
Example: StringTokenizer
String inputLine = keyboard.nextLine();
StringTokenizer wordFinder =
new StringTokenizer(inputLine, " \n.,");
while(wordFinder.hasMoreTokens())
{
System.out.println(wordFinder.nextToken());
}
Entering "Question,2b.or !tooBee."
gives this output:
Chapter 9
Question
2b
or
!tooBee
16
Java Tip: Testing for the End
of a Text File
• When method readLine in class BufferedReader
attempts to read beyond the end of a file, the
method returns the value null.
• When method read attempts to read beyond
the end of a file, the method returns the value
-1.
Chapter 9
17
Using the File Class, cont.
Chapter 9
18
Binary Files
• Binary files store data in the same format
used for main memory.
• Bytes in main memory and bytes in binary
files are read similarly, which leads to
efficiency.
• Binary files created by a Java program on
one computer can be read by a Java program
on a different computer.
Chapter 9
19
Binary Files, cont.
• Class ObjectInputStream and class
ObjectOutputStream are used to process binary
files.
– Data is read or written, one byte at a time.
– Numbers and characters are converted
automatically to bytes for storage in a
binary file.
– Data in files can be treated as Java
primitive data types, as strings, or as other
objects.
Chapter 9
20
Opening a Binary File
• syntax
ObjectOutputStream Output_Stream_Name =
new ObjectOutputStream
(new FileOutputStream(File_Name));
• example
ObjectOutputStream myOutputStream =
new ObjectOutputStream
(new FileOutputStream
(“myfile.dat”));
Chapter 9
21
ObjectOutputStream
Chapter 9
22
Output to Binary Files Using
ObjectOutputStream,
cont.
• The numbers are not in human-readable form
because there are no lines or other
separators.
Chapter 9
23
Some Methods in Class
ObjectOutputStream
• to create
public ObjectOutputStream(OutputStream
streamObject)
• to create a stream
new ObjectOutputStream
(new FileOutputStream
(File_Name_or_File_Object))
• to write a primitive type
public void writeInt(int n) throws
IOException
Chapter 9
24
Some Methods in Class
ObjectOutputStream,
cont.
• to write a primitive type, cont.
public void writeLong(long n) throws
IOException
public void writeDouble(double x)
throws IOException
public void writeFloat(float x)
throws IOException
Chapter 9
25
Some Methods in Class
ObjectOutputStream,
cont.
public void writeChar(int n)
throws IOException
public void writeBoolean(boolean b)
throws IOException
• to write a String
public void writeUTF(String aString)
throws IOException
Chapter 9
26
Some Methods in Class
ObjectOutputStream,
cont.
•
•
•
•
There is no method writeString.
Instead, use method writeUTF.
UTF stands for Unicode Text Format.
UTF provides short, efficient codes for ASCII
characters.
Chapter 9
27
Some Methods in Class
ObjectOutputStream,
cont.
• To write an object
public void writeObject(Object
anObject)
throws IOException,
NotSerializableException,
InvalidClassException
• to close
public void close() throws IOException
Chapter 9
28
Different Types in the Same
File
• Different types can be written to the same file.
• However, the different types must be read
from the file just as they were written to the
file.
Chapter 9
29
Reading Input from a Binary
File Using
ObjectInputStream
• A file written using ObjectOutputStream can be
read using ObjectInputStream.
• The methods in class ObjectInputStream
correspond to the methods in class
ObjectOutputStream.
Chapter 9
30
Some Methods in Class
ObjectInputStream
• to create
ObjectInputStream
(InputStream streamObject)
• to create a stream
new ObjectInputStream (new
FileInputStream
(File_Name_or_File_Object)
• to read a primitive type
public int readInt() throws IOException
Chapter 9
31
Some Methods in Class
ObjectInputStream, cont.
• to read a primitive type, cont.
public long readLong()
throws IOException
public double readDouble()
throws IOException
public float readFloat()
throws IOException
public char readChar()
throws IOException
public boolean ReadBoolean()
throws IOException
Chapter 9
32
Some Methods in Class
ObjectInputStream, cont.
• to read a String
public String readUTF()
throws IOException
• to read an object
public Object readObject()
throws ClassNotFoundException,
InvalidClassException,
OptionalDataException, IOException
• to close
public void close() throws IOException
Chapter 9
33
Opening an Input File
• syntax
ObjectInputStream Input_Stream_Name =
new ObjectInputStream(new
FileInputStream(File_Name));
• example
ObjectInputStream myInputStream = new
ObjectInputStream(new
FileInputStream(“myfile.dat”));
Chapter 9
34
The EOFException Class
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.
• ObjectInputStream
Chapter 9
35
The EOFException Class
Chapter 9
36
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.
Chapter 9
37
The Classes
FileInputStream and
FileOutputStream
• We used stream class FileInputStream when
we created a stream of class
ObjectInputStream.
• We used stream class FileOutputStream when
we created a stream of class
ObjectOutputStream.
Chapter 9
38
Binary I/O of Class Objects
• Using method writeObject of class
ObjectOutputStream you can output class
objects to a binary file, and then read objects
from the file using method readObject of class
ObjectInputStream.
• However, the class being written and read
must be serializable.
Chapter 9
39
Binary I/O of Class Objects,
cont.
• To make a class serializable, add implements
Serializable to the class heading.
• example
public class SomeClass implements
Serializable
• The Serializable interface is available after
importing java.io.*
Chapter 9
40
Binary I/O of Class Objects,
Chapter 9
41
Chapter 9
42
Files and toString
• Method toString provides convenient output
to the screen and to a text file.
• However, method toString is not needed for
object I/O to a binary file.
Chapter 9
43
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
44
Graphics Supplement
Chapter 9
45
Graphics Supplement, cont.
Chapter 9
46
Graphics Supplement, cont.
Chapter 9
47
Graphics Supplement, cont.
Chapter 9
48
Summary
• You have become familiar with the concept of
an I/O stream.
• You now understand the difference between
binary files and text files.
• You have learned how to save data in a file.
• You have learned how to read data from a
file.
Chapter 9
49
Summary, cont.
• You have learned how use the classes
ObjectOutputStream and ObjectInputStream to
read and write class objects with binary files.
Chapter 9
50