Chapter 17 Files, Streams and Object Serialization

Download Report

Transcript Chapter 17 Files, Streams and Object Serialization

Java How to Program, 10/e
© Copyright 1992-2015 by Pearson Education, Inc. All Rights
Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

Data stored in RAM is temporary
 It’s lost when a local variable goes out of scope or when the
program terminates


For long term retention of data, computers use files.
Computers store files on secondary storage devices
 Solid state drives, hard disks, optical disks, flash drives and
magnetic tapes.

Data maintained in files is persistent data because it
exists beyond the duration of program execution.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

Ultimately, a computer processes data items as
combinations of zeros and ones
 It’s simple and economical for engineers to build electronic
devices that can assume two stable states - one representing 0
and the other representing 1.

The simplest data item assumes the value 0 or the value
1.
 Such a data item is called a bit.
 Short for “binary digit” - a digit that can assume one of two
values.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
4

Programmers prefer to work with decimal digits (0–9),
letters (A–Z and a–z), and special symbols (e.g., $, @,
%, &, *, (, ), –, +, ", :, ? and / ).
 Known as characters.




Character set - the set of all the characters used to
write programs and represent data items.
Java uses Unicode characters that are composed of two
bytes, each byte is eight bits.
Java type byte can be used to represent byte data.
Unicode contains characters for many of the world’s
languages.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
5






Fields are composed of characters, numbers, bytes, …
A field is a group of data items of the same type that
conveys meaning.
Data items form a data hierarchy that becomes larger
and more complex in structure as we progress from bits
to characters to fields, and so on.
Typically, several fields compose a record
(implemented as a class in Java).
A record is a group of related fields.
A file is a group of related records or general data.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
6


To facilitate retrieving specific records from a file, at
least one field in each record may be chosen as a
record key.
A record key identifies a record as belonging to a
particular person or entity and is unique to each record
 Typically used to search and sort records.

There are many ways to organize records in a file. The
most common is called a sequential file, in which
records are stored in order by the record key field.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
7


A group of related data files is called a database.
A collection of programs designed to create and
manage databases is called a database management
system (DBMS). .
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
8




To read data from or write data to a file, we must create
one of the Java stream objects and attach it to the file.
A stream is a sequence of data items, usually 8-bit
bytes.
Java has two types of streams: an input stream and an
output stream.
An input stream has a source from which the data items
come, and an output stream has a destination to which
the data items are going.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



Java views each file as a sequential stream of bytes
(Fig. 15.1).
Every operating system provides a mechanism to
determine the end of a file, such as an end-of-file
marker or a count of the total bytes in the file that is
recorded in a system maintained administrative data
structure.
A Java program simply receives an indication from the
operating system when it reaches the end of the stream
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.






File streams can be used to input and output data as bits,
bytes, characters, ..., objects.
Streams that input and output bytes are known as byte
based streams, representing data in its binary format.
Streams that input and output characters are known as
character based streams, representing data as a sequence
of characters.
Files that are created using byte based streams are referred
to as binary files.
Files created using character based streams are referred to
as text files. Text files can be read by text editors.
Binary files are read by programs that understand the
specific content of the file and the ordering of that content.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

Prior to using a file, Java program must open this file by
creating an stream type object and associating a stream of
bytes or characters with it.
 Streams also associate with other devices – keyboard, network, ...

JVM always creates three stream objects when a program
begins executing:
 System.in (the standard input stream object) normally inputs bytes
from the keyboard.
 System.out (the standard output stream object) normally outputs
character data to the screen.
 System.err (the standard error stream object) normally outputs
character based error messages to the screen.

Class System provides methods setIn, setOut and setErr to
redirect the standard input, output and error streams,
respectively.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


Java programs perform file processing by using classes
from package java.io and the subpackages of
java.nio.
Includes definitions for stream classes, e.g.





FileInputStream (for byte based input from a file)
FileOutputStream (for byte based output to a file)
FileReader (for character based input from a file)
FileWriter (for character based output to a file)
You open a file by creating an object of one of these
stream classes. The object’s constructor opens the file.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


Class File provides information about files and
directories.
Character based input and output can be performed
using classes Scanner and Formatter.
 Class Scanner is used extensively to input data from the
keyboard. This class can also read data from a file.
 Class Formatter enables formatted data to be output to any
text-based stream in a manner similar to method
System.out.printf.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
Java allows to perform input and output of objects or
variables of primitive data types without having to worry
about the details of converting such values to byte format.
 To perform such input and output, objects of classes
ObjectInputStream and ObjectOutputStream can be used
together with the byte based file stream classes
FileInputStream and FileOutputStream.
 The complete hierarchy of classes in package java.io can be
viewed in the online documentation at
http://download.oracle.com/javase/8/docs/api/java/io/package
-tree.html

© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
Java SE 8 Adds Another Type of Stream
 Chapter 17, Java SE 8 Lambdas and Streams,
introduces a new type of stream that’s used to process
collections of elements (like arrays and ArrayLists),
rather than the streams of bytes we discuss in this
chapter’s file processing examples.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

Interfaces Path and DirectoryStream and classes
Paths and Files (all from package
java.nio.file) are useful for retrieving
information about files and directories on disk:
 Path interface—Objects of classes that implement this
interface represent the location of a file or directory. Path
objects do not open files or provide any file processing
capabilities.
 Paths class—Provides static methods used to get a Path
object representing a file or directory location.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
 Files class—Provides static methods for common file
and directory manipulations, such as copying files; creating
and deleting files and directories; getting information about
files and directories; reading the contents of files; getting
objects that allow you to manipulate the contents of files and
directories; and more
 DirectoryStream interface—Objects of classes that
implement this interface enable a program to iterate through
the contents of a directory.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.




A file or directory’s path specifies its location on disk.
The path includes some or all of the directories leading
to the file or directory.
An absolute path contains all directories, starting with
the root directory, that lead to a specific file or
directory.
Every file or directory on a particular disk drive has the
same root directory in its path.
A relative path is “relative” to another directory—for
example, a path relative to the directory in which the
application began executing.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



An overloaded version of Files static method get uses a URI
object to locate the file or directory.
A Uniform Resource Identifier (URI) is a more general form
of the Uniform Resource Locators (URLs) that are used to
locate websites.
On Windows platforms, the URI
file://C:/data.txt
identifies the file data.txt stored in the root directory
of the C: drive. On UNIX/Linux/MAC platforms, the URI
file:/home/student/data.txt
identifies the file data.txt stored in the home directory
of the user student.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

ch15\fig15_02\FileAndDirectoryInfo.java class prompts the
user to enter a file or directory name, then uses classes Paths
and Files and interfaces Path and DirectoryStream
to output information about that file or directory.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

A separator character is used to separate directories and
files in a path.
 On a Windows computer, the separator character is a backslash \.
 On a UNIX, Linux or Mac OS X system, it’s a forward slash /.


Java processes both characters mostly correctly in a path
name.
For example, if we were to use the path
c:\Program Files\Java\jdk1.6.0_11\demo/jfc
which employs each separator character, Java
would still process the path properly.

But there may be other problems, e.g. a blank in the folder name.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

When building Strings that represent path information,
a safe approach is to use File.separator to obtain
the local computer’s proper separator character.
 This constant returns a String consisting of one
character - the proper separator for the system.

© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


Sequential access files store records in order by the
record key field.
Text files are human readable files.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

Java imposes no structure on a file
 Notions such as records do not exist as part of the Java
language.
 You must structure files to meet the requirements of your
applications.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



Formatter class outputs formatted String to the
specified stream.
The constructor with one String argument receives
the name of the file, including its path.
 If a path is not specified, the JVM assumes that the
file is in the current directory (from which the
program was executed or NetBeans project
directory if the program was executed inside
NetBeans).
If the file does not exist, it will be created.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


If an existing file is opened, its contents are
truncated (discarded).
ch15\TextFileApps\CreateTextFile.java
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



A SecurityException occurs if the user does not have
permission to write data to the file.
A FileNotFoundException occurs if the file does not exist and a
new file cannot be created.
static method System.exit terminates an application
 An int argument of 0 indicates successful program
termination.
 A nonzero value normally indicates that an error has occurred.
 The argument is useful if the program is executed from a
batch file on Windows or a shell script on UNIX/Linux/Mac
OS X.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



Scanner method hasNext determines whether the endof-file key combination has been entered.
A NoSuchElementException occurs if the data being
read by a Scanner method is in the wrong format or if
there is no more data to input.
Formatter method format works similar to
System.out.printf

A FormatterClosedException occurs if an attempt is
made to write to a file using an already closed
Formatter object.

Formatter method close closes the file
 If method close is not called explicitly, the operating system
normally will close the file when program execution terminates.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.






Different platforms use different line separator characters.
On UNIX/Linux/Mac OS X, the line separator is a newline
character ’\n’.
On Windows, it is a combination of a carriage return and a
line feed characters represented as “\r\n”.
You can use the %n format specifier in a format control
string to output a platform specific line separator.
Method System.out.println outputs a platform
specific line separator after its argument.
Regardless of the line separator used in a text file, a Java
program can still recognize the lines of text and read them.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



To read the file data back correctly, we always must
know the order of the data stored and the data types!
The application in Fig. 15.6 reads records from the
file "clients.txt" created by the application of
Section 15.4.1 and displays the record contents.
ch15\TextFileApps\ReadTextFile.java
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

Scanner class can be used to read data sequentially from a text
file
 Pass File object representing file to be read to Scanner
constructor.
 FileNotFoundException occurs if file cannot be found.
 Data is read from file using same methods as for keyboard input –
nextInt, nextDouble, next, etc.
 IllegalStateException occurs if attempt is made to read from
closed Scanner object.
 Scanner method hasNext determines whether the end-of-file key
combination has been entered/reached.
 A NoSuchElementException occurs if the data being read by one
of the Scanner methods is in the wrong format or if there is no
more data to input.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



To retrieve data sequentially from a file, programs
start from the beginning of the file and read all the
data consecutively until the desired information is
found.
It might be necessary to process the file sequentially
several times (from the beginning of the file) during
the execution of a program.
Class Scanner does not allow repositioning to the
beginning of the file.
 The program must close the file and reopen it.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


ch15\TextFileApps\CreditInquiry.java
ch15\TextFileApps\MenuOption.java
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.





The data in many sequential files cannot be modified
without the risk of destroying other data in the file.
If the name “White” needed to be changed to
“Worthington,” the old name cannot simply be
overwritten, because the new name requires more space.
Fields in a text file and hence records can vary in size.
Records in a sequential access file are not normally updated
in place. Instead, the entire file is usually rewritten.
Rewriting the entire file is very inefficient to update just
one record, but reasonable if a substantial number of
records need to be updated.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.





In text files Java data type information is being lost.
To read an entire object from or write an entire object to a file,
Java provides object serialization.
A serialized object is represented as a sequence of bytes that
includes the object’s data and its type information.
After a serialized object has been written into a file, it can be
read from the file and deserialized to recreate the object in
memory.
Java arrays are objects so, instead of processing array elements
individually, it is possible to save to and read from a file the
whole array with a single Java statement.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


Classes ObjectInputStream and ObjectOutputStream,
which implement the ObjectInput and ObjectOutput
interfaces respectively, enable entire objects to be
read from or written to a stream with a single method
call.
To use serialization with files, initialize
ObjectInputStream and ObjectOutputStream objects
with FileInputStream and FileOutputStream objects
as constructor arguments.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



ObjectOutput interface method writeObject takes an Object
instance as an argument and writes its information to an
OutputStream.
A class that implements ObjectOutput (such as
ObjectOutputStream) declares this method and ensures that
the object being output implements Serializable interface.
ObjectInput interface method readObject reads and returns
a reference to an Object from an InputStream.
 After an object has been read, its reference should be cast to the
object’s actual type.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


Only objects of classes that implement interface
Serializable can be serialized and deserialized with
ObjectOutputStream and ObjectInputStream.
Interface Serializable is a tagging interface.
 It does not contain any methods.


A class that implements Serializable is tagged as being
a Serializable object.
An ObjectOutputStream cannot output an object unless
it is a Serializable object – the code will not compile.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


ch15\SerializationApps\Account.java
ch15\SerializationApps\CreateSequentialFile.java
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.




In a class that implements Serializable interface,
every data field must be Serializable.
Any one that is not must be declared transient so it
will be ignored during the serialization process.
All primitive type variables are serializable.
For reference type variables, check the class’s
documentation (and possibly its superclasses) to
ensure that the type is Serializable.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


The program in Fig. 15.11 reads records from a file
created by the program in Section 15.5.1 and displays
the contents.
ch15\SerializationApps\ReadSequentialFile.java
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



ObjectInputStream method readObject reads an
Object from a file.
Method readObject throws an EOFException if an
attempt is made to read beyond the end of the file.
Casting of the return value of readObject throws a
ClassNotFoundException if the class for the object
being read is not castable to the selected type.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



Class JFileChooser displays a dialog that enables the
user to easily select files or directories.
ch15\fig15_12_13\JFileChooserDemo.java
ch15\fig15_12_13\JFileChooserTest.java
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.






JFileChooser method setFileSelectionMode specifies what the
user can select from the fileChooser.
JFileChooser static constant FILES_AND_DIRECTORIES
indicates that files and directories can be selected.
Other static constants include FILES_ONLY (the default) and
DIRECTORIES_ONLY.
Method showOpenDialog displays a JFileChooser dialog titled
Open, with Open and Cancel buttons (to open a file/directory
or dismiss the dialog, respectively).
JFileChooser dialog is a modal dialog.
Method showOpenDialog returns an integer specifying which
button (Open or Cancel) the user clicked to close the dialog.
 CANCEL_OPTION constant specifies that user clicked Cancel button

JFileChooser method getSelectedFile returns the selected file as
a File object.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.

This section overviews additional interfaces and classes
(from package java.io) for byte based input and
output streams and character based input and output
streams.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


InputStream and OutputStream are abstract classes
that declare methods for performing byte based input
and output, respectively.
Pipes are synchronized communication channels
between threads.
 PipedOutputStream (a subclass of OutputStream) and
PipedInputStream (a subclass of InputStream) establish pipes
between two threads in a program.
 One thread sends data to another by writing to a
PipedOutputStream.
 The target thread reads information from the pipe via a
PipedInputStream.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



A FilterInputStream filters an InputStream, and a
FilterOutputStream filters an OutputStream.
Filtering means simply that the filter stream provides
additional functionality, such as aggregating data
bytes into meaningful primitive type units.
FilterInputStream and FilterOutputStream are
typically extended, so some of their filtering
capabilities are provided by their subclasses.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


A PrintStream (a subclass of FilterOutputStream)
performs text output to the specified stream.
System.out and System.err are PrintStream instances.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.




Usually, programs read data as aggregates of bytes that
form ints, floats, doubles, and so on.
Java programs can use several classes to input and
output data in aggregate form.
Interface DataInput describes methods for reading
primitive types from an input stream.
Classes DataInputStream and RandomAccessFile each
implement this interface to read sets of bytes and
process them as primitive type values.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


Interface DataOutput describes a set of methods for
writing primitive types to an output stream.
Classes DataOutputStream (a subclass of
FilterOutputStream) and RandomAccessFile each
implement this interface to write primitive type
values as bytes.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.


Buffering is an I/O performance enhancement technique.
With a BufferedOutputStream, each output operation is
directed to an in-memory buffer
 holds the data of many output operations.




Transfer to the output device is performed in one large
physical output operation each time the buffer fills.
The output operations directed to the output buffer in
memory are often called logical output operations.
A partially filled buffer can be forced out to the device at
any time by invoking the stream object’s flush method.
Using buffering can greatly increase the performance of an
application.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.




With a BufferedInputStream, many “logical”
chunks of data from a file are read as one large
physical input operation into a memory buffer.
As a program requests each new chunk of data, it’s
taken from the buffer.
This procedure is sometimes referred to as a logical
input operation.
When the buffer is empty, the next actual physical input
operation from the input device is performed.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



Java stream I/O includes capabilities for inputting
from byte arrays in memory and outputting to
byte arrays in memory.
A ByteArrayInputStream (a subclass of
InputStream) reads from a byte array in
memory.
A ByteArrayOutputStream (a subclass of
OutputStream) outputs to a byte array in
memory.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



A SequenceInputStream (a subclass of InputStream)
logically concatenates several InputStreams.
The program sees the group of streams as one
continuous InputStream.
When the program reaches the end of one input
stream, that stream closes, and the next stream in the
sequence opens automatically.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.





The Reader and Writer abstract classes represent Unicode two
byte, character based streams.
Most of the byte based streams have corresponding character
based concrete Reader or Writer classes.
Classes BufferedReader (a subclass of abstract class Reader)
and BufferedWriter (a subclass of abstract class Writer)
enable buffering for character based streams.
Classes CharArrayReader and CharArrayWriter read and
write, respectively, a stream of characters from/to a char array.
A LineNumberReader (a subclass of BufferedReader) is a
buffered character stream that keeps track of the number of
lines read.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.






An InputStream can be converted to a Reader via class
InputStreamReader.
An OuputStream can be converted to a Writer via class
OutputStreamWriter.
Classes FileReader and class FileWriter read characters
from and write characters to a file.
Classes PipedReader and class PipedWriter implement
piped character streams for transferring data between
threads.
Classes StringReader and StringWriter read characters
from and write characters to Strings.
A PrintWriter writes characters to a stream.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.



File I/O exception handling and file close are a must – always
use try-catch-finally or try-with-resources blocks.
All Java file I/O exceptions are checked exceptions – your
code won’t compile if these exceptions are not properly
handled.
Correct file I/O sequence:
 Open file. If failure stop and try to recover.
 Read or write.
 Close file.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
11
1




Don’t ever try to read from/write to a file if file open failed.
Files must be always closed explicitly by the program to
release resources ASAP. Always place the call to the close
method in the finally block or use try-with-resources
technique.
To read from a file, one needs to know how the file was
created and written to. Always take the write operation into
consideration when designing the file read code.
Java file I/O uses decorator pattern to simplify code design –
an instance of one class can be passed as a constructor
argument when creating instances of other I/O classes.
© Copyright 1992-2015 by Pearson
Education, Inc. All Rights Reserved.
11
2