Session9 IO
Session9 IO
I/O
I/O
Java does strong, flexible support for I/O as it
relates to files and networks.
Javas I/O system is cohesive and consistent.
Java programs perform I/O through streams.
Most real applications are either graphically
oriented programs that rely on Javas Abstract
Window ToolKit (AWT) or Swing for user
interaction, or Web applications.
Streams
A stream is an abstraction that either produces or
consumes information. That is, it is an object that
either delivers data to its destination (screen, file,
etc.) or that takes data from a source (keyboard,
file, etc.)
It acts as a buffer between the data source and
destination.
Java implements streams within class hierarchies
defined in the java.io package.
A stream is linked to a physical device by
the Java I/O system.
All streams behave in the same manner, even if
the actual physical devices to which they are
linked differ.
Thus, the same I/O classes and methods can be
applied to any type of device.
Failure to explicitly close a stream can result in
memory leaks because of unused resources
remaining allocated, i.e. resource starvation.
Java defines 2 types of streams: byte-stream and
character-stream.
The Predefined Streams
All Java programs automatically imports the
java.lang package. This package defines a class
called System, which encapsulates several
aspects of the run-time environment.
System contains 3 predefined stream variables:
in, out, and err, which are declared as public,
static and final within System. Thus, they can be
used by any other part of a program and without
reference to a specific System object.
Byte Streams
Byte streams provide a convenient means for
handling input and output of bytes. They are
used when reading or writing binary data.
Byte streams are defined by using 2 class
hierarchies. At the top are 2 abstract classes:
InputStream and OutputStream.
Each of these abstract classes has several
concrete subclasses that handle the differences
among various devices.
INPUTSTREAM CLASSES OUTPUTSTREAM CLASSES
BufferedInputStream BufferedOutputStream
ByteArrayInputStream ByteArrayOutputStream
DataInputStream DataOutputStream
FileInputStream FileOutputStream
FilterInputStream FilterOutputStream
InputStream OutputStream
ObjectInputStream ObjectOutputStream
PipedInputStream PipedOutputStream
PushbackInputStream PrintStream
SequenceInputStream
Byte Stream Classes in java.io
These abstract classes define several key
methods that the other stream classes
implement.
Two of the most important are read() and write(),
which, respectively, read and write bytes of data.
Each has forms that are abstract and must be
overridden by derived stream classes.
Console input can be performed using the byte
stream by reading from System.in, which is an
object of type InputStream and refers to the
standard input, which is the keyboard by default.
System.out is an object of type
PrintStream and refers to the standard
output stream. By default, this is the console.
System.err is an object of type PrintStream and
refers to the standard error stream, which also is
the console by default.
These are byte streams, even though they are
typically used to read and write characters from
and to the console.
Character Streams
Character streams provide a convenient means
for handling input and output of characters. They
use Unicode, and hence can be internationalized.
Character streams are defined by using 2 class
hierarchies. At the top are 2 abstract classes:
Reader and Writer.
These abstract classes handle Unicode character
streams. Java has several concrete subclasses of
each of these.
INPUTSTREAM CLASSES OUTPUTSTREAM CLASSES
BufferedReader BufferedWriter
CharArrayIReader CharArrayWriter
StringReader StringWriter
FileReader FileWriter
FilterReader FilterWriter
InputStreamReader OutputStreamWriter
Reader Writer
PipedReader PipedWriter
PushbackReader PrintWriter
LineNumberReader
Character Stream Classes in java.io
These abstract classes define several key
methods that the other stream classes
implement. Two of the most important are read()
and write(), which read and write characters of
data, respectively.
Each has forms that are abstract and must be
overridden by derived stream classes.
The byte streams System.in, System.out and
System.err can be wrapped within character-
based streams.
BufferedReader class supports a buffered
input stream and has the general form:
BufferedReader (Reader inputReader)
Reader is an abstract class. One of its concrete
subclasses is InputStreamReader, which converts
bytes to characters. An InputStreamReader object
that is linked to System.in can be obtained using
the constructor:
InputStreamReader(InputStream inputStream)
Putting it all together creates a
BufferedReader that is connected to the
keyboard.
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Now, br is a character-based stream that is linked
to the console through System.in.
To read a character from a BufferedReader, read()
is used.
int read() throws IOException
Each time that read() is called, it reads a
character from the input stream and
return it as an integer value.
It returns -1 when the end of the stream is
encountered.
It can throw IOExceptions, which are simply
thrown out of main().
To read a string from the keyboard, the
BufferedReader class member readLine() is used.
String readLine() throws IOException
File I/O
Advantages:
permanent copy
output from one program can be input
to another
input can be automated (rather than
entered manually
Reading & Writing Files
FileInputStream and FileOutputStream are 2
classes that create byte streams linked to files.
To open a file, an object of one of these classes is
created, specifying the name of the file as an
argument to the constructor.
FileInputStream(String filename or path) throws
FileNotFoundException
If the file does not exist when an input stream is
created, a FileNotFoundException is thrown.
To read from a file, the read() defined
within the FileInputStream is used:
int read() throws IOException
Each time the read() is called, a single byte is read
from the file and returns the byte as an integer.
read() returns -1 when the end of file is
encountered. It can throw an IOException.
FileOutputStream(String filename) throws
FileNotFoundException
If the file cannot be opened or created
when an output stream is created, a
FileNotFoundException is thrown.
When an output file is opened, any preexisting
file by the same name is destroyed.
The FileNotFoundException is a subclass of
IOException.
To write to a file, write() defined by
FileOutputStream is used.
void write(int byteval) throws IOException
This method writes the byte specified by
byteval to the file. Only the low order 8
bits are written to the file.
If an error occurs during writing, an IOException is
thrown.
At the end, the file must be closed using close().
void close() throws IOException
Closing a file releases the system resources
allocated to the file, allowing them to be used by
another file.
With this traditional approach, close() is
typically called within a finally block.
A new feature is introduced in JDK 7 that
manages resources by automating the closing
process. This is referred to as automatic resource
management (ARM) and is based on an expanded
version of the try statement.
This new form of try is called try-with-resources
statement.
The try-with-resources statement can be
used only with those resources that
implement the AutoCloseable interface defined
by java.lang.
This interface defines the close() method.
AutoCloseable is inherited by the Closeable
interface in java.io. Both interfaces are
implemented by the stream classes.
Thus, try-with-resources can be used when
working with streams, including file streams.
try(resource-specification) {
//use the resource }
Resource-specification is a statement that
declares and initializes a resource, such a file
stream. This resource is implicitly final.
It consists of a variable declaration in which the
variable is initialized with a reference to the
object being managed.
This variable is local to the try block, being
created when the try is entered.
Also, more then one resource can be managed
within a single try statement, by
separating each resource specification with a
semicolon.
However, when the try block ends, the resource is
automatically released, i.e the stream associated
with the variable is automatically closed by an
implicit call to close().
This form of try block can also include catch and
finally clauses.