Download Chapter 9 Streams and File I/O

Document related concepts

Library (computing) wikipedia , lookup

Name mangling wikipedia , lookup

Object-oriented programming wikipedia , lookup

Class (computer programming) wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

C Sharp syntax wikipedia , lookup

Diff wikipedia , lookup

Transcript
Streams and File I/O
Chapter 9
Outline
•
•
•
•
•
Overview of Streams and File I/O
Text-File I/O
Using the File Class
Basic Binary-File I/O
Object I/O with Object Streams
Overview of Streams and File
I/O: Outline
• The Concept of a Stream
• Why Use Files for I/O?
• Differences Between Text Files and Binary
Files
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.
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.
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.
• This chapter discusses steams that connect
programs to files.
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.
• 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.
Text Files and Binary Files,
cont.
• Text files usually appear to be the same on
all computers.
• Binary files usually differ from machine to
machine and from programming language to
programming language.
– Normally, the computer and programming
language used to create the file must be
used to read the file.
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.
• Though text files can be read and written
using an editor, binary files must be read and
written by a program.
Text-File I/O: Outline
•
•
•
•
Text-File Output with PrintWriter
Text-File Input with BufferedReader
The StringTokenizer Class
The Classes FileReader and FileOutputStream
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.
Text-File Output with
PrintWriter, cont.
Text-File Output with
PrintWriter, cont.
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 is lost.
– If the named file does not exist, a new
empty file is created (and named out.txt,
for example).
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));
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.
Some Methods in Class
PrintWriter
• constructor
PrintWriter(OutputStream streamObject)
• to create a stream
new PrintWriter(new
FileOutputStream(File_Name))
• to append new text
new PrintWriter(new
FileOutputStream(File_Name,
true))
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()
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.
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.
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.
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.
Text-file Input with
BufferedReader, cont.
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.
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 read a single character from the file
and to treat it as a character
char next = (char)(inputStream.read());
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()
Programming Example:
Reading a File Name from the
Keyboard
• A user may need to enter a file name at the
keyboard at the time a program is run.
Programming Example:
Reading a File Name from the
Keyboard, cont.
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.
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.
Java Tip: Using Path Names,
cont.
• example - UNIX
/user/smith/home.work1/data.txt
…
new FileReader
(“/user/smith/home.work1/data.txt”)…
• example - Windows
D:\homework\hw1\data.txt
…
new FileReader
(“D:\\homework\\hw1\\data.txt”)…
Java Tip: Using Path Names,
cont.
• The \\ would be used if the path name is
hardcoded, but the \ would be used if the
path name is entered from the keyboard.
• A Java program will accept a path name
written in either Windows or UNIX format,
even if a computer is using an operating
system that does not match the syntax.
...(“D:/homework/hw1/data.txt”)...
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.
The StringTokenizer
Class, cont.
• Tokens are nonwhitespace characters.
• example
StringTokenizer tokenizer = new
StringTokenizer(“Read my lips!”)
while (tokenizer.hasMoreTokens() {
System.out.println
(tokenizer(nextToken());
}
• This will produce
Read
my
lips!
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.,!”);
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()
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.
Java Tip: Testing for the End
of a Text File
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.
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.
• example
– BufferedReader inputStream =
–
new BufferedReader
–
(new FileReader(“story.txt”);
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.
The Classes FileReader
and FileOutputStream,
cont.
• example
PrintWriter OutputStream =
new PrintWriter
(new FileOutputStream
(“stuff.txt”);
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.
• The File class is like a wrapper class for
strings which are file names.
– example
new File(“treasure.txt”)
Using the File Class, cont.
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.
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()
Basic Binary-File I/O: Outline
• Output to Binary Files Using
ObjectOutputStream
• (optional) Some Details About writeUTF
• Reading Input from a Binary File Using
ObjectInputStream
• The EOFException Class
• The Classes FileInputStream and
FileOutputStream
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.
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.
Opening a Binary File
• syntax
ObjectOutputStream Output_Stream_Name =
new ObjectOutputStream
(new FileOutputStream(File_Name));
• example
ObjectOutputStream myOutputStream =
new ObjectOutputStream
(new FileOutputStream
(“myfile.dat”));
Output to Binary Files Using
ObjectOutputStream
Output to Binary Files Using
ObjectOutputStream,
cont.
• The numbers are not in human-readable form
because there are no lines or other
separators.
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
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
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
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
• to flush
public void flush() throws IOException
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.
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.
(optional) Some Details About
writeUTF
• Method writeUTF uses different numbers of
bytes to store strings of different lengths in a
file.
• However, there are no separators between
data items in a binary file.
• Java resolves this problem by writing extra
information at the start of each string (i.e. the
number of bytes used to write the string).
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.
• class BinaryInputDemo
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
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
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
Opening an Input File
• syntax
ObjectInputStream Input_Stream_Name =
new ObjectInputStream(new
FileInputStream(File_Name));
• example
ObjectInputStream myInputStream = new
ObjectInputStream(new
FileInputStream(“myfile.dat”));
Reading Binary Files and Text
Files
• Do not attempt to read a binary file as if it
were a text file (using BufferedReader) or a text
file as it if were a binary file (using
ObjectInputStream).
– For the buffering, BufferedInputStream can
be used.
DataInputStream and
DataOutputStream
• ObjectInputStream and
ObjectOutputStream uses JAVA`s own
file header for the object save & load.
– However, they can`t handle general binary files.
• DataInputStream and
DataOutputStream can handle general
binary files.
– However, they can`t save and load JAVA
objects directly.
Defining a Method to Open a
Stream
public static ObjectOutputStream
openFile() throws IOException
{
ObjectOutputStream tempStreamName;
System.out.println(“Enter file name: “);
Scanner keyboard = new
Scanner(System.in);
String fileName = keyboard.next();
tempStreamName = new
ObjectOutputStream(new
FileOutputStream(fileName));
return tempStreamName;
}
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
The EOFException Class
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.
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.
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
The Classes
FileInputStream and
FileOutputStream, cont.
• You connect an ObjectInputStream to a file
using a string name in two steps.
– Create an object of class FileOutputStream
– Use this object of class FileOutputStream to
create an object of class ObjectOutputStream
The Classes
FileInputStream and
FileOutputStream, cont.
• example
ObjectOutputStream outputStream = new
ObjectOutputStream(new
FileOutputStream(“numbers.dat”));
Programming Example:
Processing a File of Binary
Data
• Ask the user for two file names.
• Read the numbers in one file, multiply each
number by two, and write the results to other
file.
Programming Example:
Processing a File of Binary
Data, cont.
Programming Example:
Processing a File of Binary
Data, cont.
Object I/O with Object
Streams: Outline
• Binary I/O of Class Objects
• The Serializable Interface
• Array Objects in Binary Files
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.
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.*
Binary I/O of Class Objects,
cont.
Binary I/O of Class Objects,
cont.
Binary I/O of Class Objects,
cont.
The Serializable Interface
• A class which is serializable effects 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.
The Serializable
Interface, cont.
• This makes file I/O more efficient and makes
files smaller.
• When read with a stream of type
ObjectInputStream, duplicate serial numbers
are returned as references to the same
object.
• When a serializable class has instance
variables of a class type, the class for the
instance variables should be serializable.
Don’t Mix Class Types
• It’s good programming practice to store data
of only one class type on any one file.
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.
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.
• You have learned how use the classes
ObjectOutputStream and ObjectInputStream to
read and write class objects with binary files.