session9 io
TRANSCRIPT
-
8/11/2019 Session9 IO
1/24
Session 9I/O
-
8/11/2019 Session9 IO
2/24
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 AbstractWindow ToolKit (AWT) or Swing for userinteraction, or Web applications.
-
8/11/2019 Session9 IO
3/24
Streams A stream is an abstraction that either produces or
consumes information. That is, it is an object thateither 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 anddestination.
Java implements streams within class hierarchiesdefined in the java.io package.
-
8/11/2019 Session9 IO
4/24
A stream is linked to a physical device bythe Java I/O system.
All streams behave in the same manner, even ifthe actual physical devices to which they arelinked differ.
Thus, the same I/O classes and methods can beapplied to any type of device. Failure to explicitly close a stream can result in
memory leaks because of unused resourcesremaining allocated, i.e. resource starvation.
Java defines 2 types of streams: byte-stream andcharacter-stream.
-
8/11/2019 Session9 IO
5/24
-
8/11/2019 Session9 IO
6/24
Byte Streams Byte streams provide a convenient means for
handling input and output of bytes. They areused when reading or writing binary data.
Byte streams are defined by using 2 classhierarchies. At the top are 2 abstract classes:InputStream and OutputStream.
Each of these abstract classes has severalconcrete subclasses that handle the differencesamong various devices.
-
8/11/2019 Session9 IO
7/24
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
-
8/11/2019 Session9 IO
8/24
These abstract classes define several keymethods 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 bytestream by reading from System.in, which is anobject of type InputStream and refers to the
standard input, which is the keyboard by default.
-
8/11/2019 Session9 IO
9/24
System.out is an object of type
PrintStream and refers to the standardoutput stream. By default, this is the console.
System.err is an object of type PrintStream and
refers to the standard error stream, which also isthe console by default.
These are byte streams, even though they aretypically used to read and write characters fromand to the console.
-
8/11/2019 Session9 IO
10/24
Character Streams Character streams provide a convenient means
for handling input and output of characters. Theyuse Unicode, and hence can be internationalized.
Character streams are defined by using 2 classhierarchies. At the top are 2 abstract classes:Reader and Writer.
These abstract classes handle Unicode characterstreams. Java has several concrete subclasses ofeach of these.
-
8/11/2019 Session9 IO
11/24
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
-
8/11/2019 Session9 IO
12/24
These abstract classes define several key
methods that the other stream classesimplement. 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.
-
8/11/2019 Session9 IO
13/24
-
8/11/2019 Session9 IO
14/24
Putting it all together creates aBufferedReader that is connected to thekeyboard.
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
-
8/11/2019 Session9 IO
15/24
Each time that read() is called, it reads acharacter from the input stream andreturn 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
-
8/11/2019 Session9 IO
16/24
File I/O Advantages:
permanent copy
output from one program can be inputto another
input can be automated (rather than
entered manually
-
8/11/2019 Session9 IO
17/24
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 anargument to the constructor.
FileInputStream(String filename or path) throwsFileNotFoundException
If the file does not exist when an input stream is
created, a FileNotFoundException is thrown.
-
8/11/2019 Session9 IO
18/24
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 isencountered. It can throw an IOException.
FileOutputStream(String filename) throwsFileNotFoundException
-
8/11/2019 Session9 IO
19/24
If the file cannot be opened or createdwhen an output stream is created, aFileNotFoundException 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
-
8/11/2019 Session9 IO
20/24
This method writes the byte specified bybyteval to the file. Only the low order 8bits 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 byanother file.
-
8/11/2019 Session9 IO
21/24
-
8/11/2019 Session9 IO
22/24
The try-with-resources statement can beused only with those resources thatimplement the AutoCloseable interface definedby java.lang.
This interface defines the close() method.AutoCloseable is inherited by the Closeableinterface in java.io. Both interfaces areimplemented by the stream classes.
Thus, try-with-resources can be used when
working with streams, including file streams.
-
8/11/2019 Session9 IO
23/24
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.
-
8/11/2019 Session9 IO
24/24
Also, more then one resource can be managedwithin a single try statement, byseparating each resource specification with asemicolon.
However, when the try block ends, the resource isautomatically released, i.e the stream associatedwith the variable is automatically closed by animplicit call to close().
This form of try block can also include catch and
finally clauses