Download Powerpoint slides

Document related concepts
no text concepts found
Transcript
Streams and File I/O
Chapter 9
Chapter 9
1
The Concept of a Stream
• Files can be used to store
– Java classes
– Java programs
– output from a program
– input for a program.
• File I/O as well as keyboard and screen I/O
are handled by streams.
Chapter 9
6
The Concept of a Stream,
cont.
• A stream is a flow of data (characters,
numbers, etc.).
• Data flowing into a program is called an input
stream.
• Data flowing out of a program is called an
output stream.
Chapter 9
7
The Concept of a Stream,
cont.
• A stream is implemented as an object.
– It delivers data to a destination such as a
file or a stream or
– it takes data from a source such as a file or
the keyboard, and delivers it to a program.
• System.out is the only output stream we have
used so far.
• Objects of class Scanner, used for keyboard
input, are streams, too.
Chapter 9
8
The Concept of a Stream,
cont.
• This chapter discusses streams that connect
programs to files.
Chapter 9
9
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
10
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
11
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
12
Text Files and Binary Files,
cont.
• However, binary files are more efficient to
process than text files.
• In Java, binary files are platformindependent.
– Binary files can be created by one
computer and read by another, combining
portability and efficiency.
Chapter 9
14
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.
Chapter 9
15
Text-File Output with
PrintWriter
• Class PrintWriter has a method println that
behaves like System.out.println
• The java.io package contains the class
PrintWriter and the other file I/O classes
discussed in this chapter.
Chapter 9
17
Text-File Output with
PrintWriter, cont.
• class TextFileOutputDemo
Chapter 9
18
Text-File Output with
PrintWriter, cont.
• A file is opened using something similar to
outputStream = new PrintWriter(
new FileOutputStream(“out.txt”));
– An empty file is connected to a stream.
– If the named file (out.txt, for example)
exists already, its old contents are lost.
– If the named file does not exist, a new
empty file is created (and named out.txt,
for example).
Chapter 9
21
Text-File Output with
PrintWriter, cont.
• Class Printwriter has no constructor that
takes a file name as an argument.
• So, we use class FileOutputStream to create a
stream and can be used as an argument to a
PrintWriter constructor.
• Syntax
PrintWriter Output_Stream_Name = new
PrintWriter (new
FileOutputStream(File_Name));
Chapter 9
22
Text-File Output with
PrintWriter, cont.
• The FileOutputStream constructor, and thus the
PrintWriter constructor invocation can throw a
FileNotFoundException, which means that the
file could not be created.
• The PrintWriter object is declared outside the
try block.
– If it were declared inside the try block, it
would be local to the try block.
Chapter 9
23
Some Methods in Class
PrintWriter
• constructor
PrintWriter(OutputStream streamObject)
• to create a new file
new PrintWriter(new
FileOutputStream(File_Name))
• to append new text to an old file
new PrintWriter(new
FileOutputStream(File_Name, true))
Chapter 9
24
Some Methods in Class
PrintWriter, cont.
• to output to the file connected to the stream
public final void
println(Almost_Anything)
public final void
print(Almost_Anything)
• To close a stream’s connection to a file
public void close()
• To flush the output stream
public void flush()
Chapter 9
25
Closing Text Files
• When a program finishes writing to or reading
from a file, it should close the file.
– examples
outputStream.close();
inputStream.close();
• If a program does not close a file before the
program ends, Java will will close it when the
program ends, provided the program ends
normally.
Chapter 9
26
Closing Text Files, cont.
• The sooner a file is closed, the less likely it is
to be damaged by being left open when a
program ends abnormally.
• If a program writes a file, it must close the file
before it attempts to read from it.
Chapter 9
27
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.
Chapter 9
29
Use toString for Text-File
Output, cont.
• class Species
Chapter 9
30
Use toString for Text-File
Output, cont.
• class TextFileObjectOutputDemo
Chapter 9
31
Text-file Input with
BufferedReader
• Class BufferedReader is the preferred stream
class for reading from a text file.
• Class BufferedReader has no constructor that
takes a filename as its argument.
– Class FileReader accepts a file name as a
constructor argument and produces a
stream that is a Reader object.
– The constructor for class BufferedReader
accepts a Reader object as an argument.
Chapter 9
33
Text-file Input with
BufferedReader, cont.
• syntax
BufferedReader Stream_Name = new
BufferedReader(new
FileReader(File_Name));
• Methods readln and read are used to read
from the file.
• The FileReader constructor, and thus the
BufferedReader constructor invocation can
throw a FileNotFoundException.
Chapter 9
34
Text-file Input with
BufferedReader, cont.
• class TextFileInputDemo
Chapter 9
35
Some Methods in Class
BufferedReader
• constructor
BufferedReader(Reader, readerObject)
• to create a stream
new BufferedReader(new
FileReader(File_Name))
• to read a line of input from the file
public String readLine() throws IOException
– If the read operation goes beyond the end
of the file, null is returned.
Chapter 9
38
Some Methods in Class
BufferedReader, cont.
• to read a single character from the file and
return it as an int value
public int read() throws IOException
– If the read operation goes beyond the end
of the file, -1 is returned.
• to read a single character from the file and to
treat it as a character
char next = (char)(inputStream.read());
Chapter 9
39
Some Methods in Class
BufferedReader, cont.
• To read a number from a text file, the number
must be read in as a string and the string
must be converted to a number.
• to close a stream’s connection to a file
public void close()
Chapter 9
40
Java Tip: Using Path Names
• When providing a file name as an argument
for opening a file, a simple file name may be
used if the file is in the same directory as the
program being run.
• A full or relative path name also can be used.
• A full path name is the complete path name,
starting from the root directory.
Chapter 9
45
Java Tip: Using Path Names,
cont.
• A relative path name is the path name
starting from the directory containing the
program.
• The way to specify path names depends
upon the operating system.
Chapter 9
46
The 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
49
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
50
The StringTokenizer
Class, cont.
• This will produce
Read
my
lips!
Chapter 9
51
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
52
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()
Chapter 9
53
Some Methods in Class
StringTokenizer, cont.
• remaining tokens
public int countTokens()
Chapter 9
54
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
55
Java Tip: Testing for the End
of a Text File
• class EOFDemo
Chapter 9
56
The Classes FileReader
and FileOutputStream
• Class FileReader is used with class
BufferedReader; class FileOutputStream is used
with class Printwriter.
• Class FileReader and class FileOutputStream
accept a file name as a constructor argument.
Chapter 9
57
The Classes FileReader
and FileOutputStream,
cont.
• Connecting a BufferedReader object to a file
using a string name requires two steps.
– First, create an object of the class
FileReader.
– Then use this object to create an object of
class BufferedReader.
Chapter 9
58
The Classes FileReader
and FileOutputStream,
cont.
• example
BufferedReader inputStream =
new BufferedReader
(new FileReader(“story.txt”);
Chapter 9
59
The Classes FileReader
and FileOutputStream,
cont.
• Producing a PrintWriter output stream from a
file using FileOutputStream requires two steps.
– First, create an object of the class
FileOutputStream.
– Then use this object to create an object of
class PrintWriter.
Chapter 9
60
The Classes FileReader
and FileOutputStream,
cont.
• example
PrintWriter OutputStream =
new PrintWriter
(new FileOutputStream
(“stuff.txt”);
Chapter 9
61
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
62
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
63
Using the File Class, cont.
class FileClassDemo
Chapter 9
64
Using the File Class, cont.
• Method canWrite determines if the operating
system will let you write to the file.
• Typically, the operating systems lets you
designate files as not writeable or as
writeable only by certain users.
Chapter 9
65
Some Methods in the Class
File
public
public
public
public
public
public
public
boolean exists()
boolean canRead()
boolean canWrite()
boolean delete()
boolean length()
String getName()
String getPath()
Chapter 9
66
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 read by a Java program on
a different computer.
Chapter 9
68
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
69
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
70
Output to Binary Files Using
ObjectOutputStream
• class BinaryOutputDemo
Chapter 9
71
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
72
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
73
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
74
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
75
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
76
Some Methods in Class
ObjectOutputStream,
cont.
• to flush
public void flush() throws IOException
Chapter 9
77
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
78
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
79
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
81
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
83
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
84
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
85
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
86
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
89
The EOFException Class
• class EOFExceptionDemo
Chapter 9
90
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
92
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
93
The Classes
FileInputStream and
FileOutputStream, cont.
and FileInputStream accept a
file name as a constructor argument.
• Neither ObjectInputStream nor
ObjectOutputStream accepts a file name as an
argument.
• FileOutputStream
Chapter 9
94
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
101
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
102
Binary I/O of Class Objects,
cont.
• class Species
Chapter 9
103
Binary I/O of Class Objects,
cont.
• class IODemo
Chapter 9
104
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
106
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
107
Graphics Supplement
• class FileOrganizer
Chapter 9
114
Graphics Supplement, cont.
• class FileOrganizer, cont.
Chapter 9
115
Graphics Supplement, cont.
• class FileOrganizer, cont.
Chapter 9
116
Graphics Supplement, cont.
Chapter 9
117