j21 java i/o stream
TRANSCRIPT
-
8/14/2019 J21 Java I/O Stream
1/76
1
J21 Java I/O StreamJ21 Java I/O Stream
-
8/14/2019 J21 Java I/O Stream
2/76
2
Topics
What is an I/O stream?
Types of Streams
Stream class hierarchy
Control flow of an I/O operation using Streams Byte streams
Character streams
Buffered streams
Standard I/O streams
Data streams
Object streams
File class
-
8/14/2019 J21 Java I/O Stream
3/76
3
What is an I/OWhat is an I/OStream?Stream?
-
8/14/2019 J21 Java I/O Stream
4/76
-
8/14/2019 J21 Java I/O Stream
5/76
5
I/O Streams
No matter how they work internally, all streamspresent the same simple model to programs thatuse them
A stream is a sequence of data
-
8/14/2019 J21 Java I/O Stream
6/76
6
Input Stream
A program uses an input stream to read data from asource, one item at a time
source:java.sun.com
-
8/14/2019 J21 Java I/O Stream
7/76
7
Output Stream
A program uses an output stream to write data to adestination, one item at time
-
8/14/2019 J21 Java I/O Stream
8/76
8
Types of StreamsTypes of Streams
-
8/14/2019 J21 Java I/O Stream
9/76
9
General Stream Types
Character and Byte Streams
Character vs. Byte
Input and Output Streams
Based on source or destination
Node and Filter Streams
Whether the data on a stream is manipulated or
transformed or not
-
8/14/2019 J21 Java I/O Stream
10/76
10
Character and Byte Streams
Byte streams For binary data
Root classes for byte streams:
The InputStream Class
The OutputStream Class
Both classes are abstract
Character streams
For Unicode characters Root classes for character streams:
The Readerclass
TheWriterclass
Both classes are abstract
-
8/14/2019 J21 Java I/O Stream
11/76
11
Input and Output Streams
Input or source streams
Can read from these streams
Root classes of all input streams:
The InputStream Class The ReaderClass
Output or sink (destination) streams
Can write to these streams
Root classes of all output streams:
The OutputStream Class
TheWriterClass
-
8/14/2019 J21 Java I/O Stream
12/76
12
Node and Filter Streams
Node streams (Data sink stream)
Contain the basic functionality of reading or writingfrom a specific location
Types of node streams include files, memory andpipes
Filter streams (Processing stream)
Layered onto node streams between threads or
processes For additional functionality- altering or managing
data in the stream
Adding layers to a node stream is called stream
chaining
-
8/14/2019 J21 Java I/O Stream
13/76
13
Stream ClassStream ClassHierarchyHierarchy
-
8/14/2019 J21 Java I/O Stream
14/76
14
Streams
InputStream
OutputStream
Reader
Writer
-
8/14/2019 J21 Java I/O Stream
15/76
15
Abstract Classes
InputStream & OutputStream
Reader & Writer
-
8/14/2019 J21 Java I/O Stream
16/76
16
InputStream Abstract Class
-
8/14/2019 J21 Java I/O Stream
17/76
17
InputStream Abstract Class
-
8/14/2019 J21 Java I/O Stream
18/76
18
Node InputStream Classes
-
8/14/2019 J21 Java I/O Stream
19/76
19
FilterInputStream Classes
-
8/14/2019 J21 Java I/O Stream
20/76
20
OutputStream Abstract Class
-
8/14/2019 J21 Java I/O Stream
21/76
21
Node OutputStream Classes
-
8/14/2019 J21 Java I/O Stream
22/76
22
FilterOutputStream Classes
-
8/14/2019 J21 Java I/O Stream
23/76
23
The ReaderClass: Methods
-
8/14/2019 J21 Java I/O Stream
24/76
24
The ReaderClass: Methods
-
8/14/2019 J21 Java I/O Stream
25/76
25
Node ReaderClasses
-
8/14/2019 J21 Java I/O Stream
26/76
26
FilterReaderClasses
-
8/14/2019 J21 Java I/O Stream
27/76
27
The WriterClass: Methods
-
8/14/2019 J21 Java I/O Stream
28/76
28
Node WriterClasses
-
8/14/2019 J21 Java I/O Stream
29/76
29
FilterWriterClasses
-
8/14/2019 J21 Java I/O Stream
30/76
-
8/14/2019 J21 Java I/O Stream
31/76
31
Control Flow of an I/O operation
Create a stream object and associate it with a data-source (data-destination)
Give the stream object the desired functionality
through stream chainingwhile (there is more information)
read(write) next data from(to) the stream
close the stream
-
8/14/2019 J21 Java I/O Stream
32/76
32
Byte StreamByte Stream
-
8/14/2019 J21 Java I/O Stream
33/76
33
Byte Stream
Programs use byte streams to perform input andoutput of 8-bit bytes
All byte stream classes are descended from
InputStream and OutputStream There are many byte stream classes
FileInputStream and FileOutputStream
They are used in much the same way; they differmainly in the way they are constructed
-
8/14/2019 J21 Java I/O Stream
34/76
34
When Not to Use Byte Streams?
Byte Stream represents a kind of low-level I/O thatyou should avoid
If the data contains character data, the best
approach is to use character streams There are also streams for more complicated data
types
Byte streams should only be used for the most
primitive I/O All other streams are based on byte stream
-
8/14/2019 J21 Java I/O Stream
35/76
35
Example: FileInputStream &FileOutputStream
public class CopyBytes {public static void main(String[] args) throws IOException {
FileInputStream in = null;FileOutputStream out = null;
try { in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt"); int c;
while ((c = in.read()) != -1) {out.write(c);
}}// More code
-
8/14/2019 J21 Java I/O Stream
36/76
36
Example: FileInputStream &FileOutputStream
finally {if (in != null) {
in.close();}
if (out != null) { out.close();
}}
}
}
-
8/14/2019 J21 Java I/O Stream
37/76
37
Simple Byte Stream input andoutput
-
8/14/2019 J21 Java I/O Stream
38/76
38
Character StreamCharacter Stream
-
8/14/2019 J21 Java I/O Stream
39/76
39
Character Stream
The Java platform stores character values usingUnicode conventions
Character stream I/O automatically translates this
internal format to and from the local character set. In Western locales, the local character set is usually
an 8-bit superset of ASCII.
All character stream classes are descended from
Reader and Writer As with byte streams, there are character stream
classes that specialize in file I/O: FileReader andFileWriter.
Ch t St
-
8/14/2019 J21 Java I/O Stream
40/76
40
Character Stream
For most applications, I/O with character streams isno more complicated than I/O with byte streams.
Input and output done with stream classesautomatically translates to and from the localcharacter set.
A program that uses character streams in place ofbyte streams automatically adapts to the localcharacter set and is ready for internationalization all without extra effort by the programmer.
If internationalization isn't a priority, you can simplyuse the character stream classes without payingmuch attention to character set issues.
Later, if internationalization becomes a priority, your
program can be adapted without extensive recoding.
-
8/14/2019 J21 Java I/O Stream
41/76
41
Example: FileReader & FileWriter
public class CopyCharacters {public static void main(String[] args) throws IOException {
FileReader inputStream = null;FileWriter outputStream = null;
try { inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;while ((c = inputStream.read()) != -1) {
outputStream.write(c);}
}
// More code
-
8/14/2019 J21 Java I/O Stream
42/76
42
Example: FileReader & FileWriter
finally {if (inputStream != null) {
inputStream.close();}
if (outputStream != null) {outputStream.close();
}}
}
}
-
8/14/2019 J21 Java I/O Stream
43/76
43
Character Stream and Byte Stream
Character streams are often "wrappers" for bytestreams
The character stream uses the byte stream to
perform the physical I/O, while the character streamhandles translation between characters and bytes.
FileReader, for example, uses FileInputStream,while FileWriter uses FileOutputStream
-
8/14/2019 J21 Java I/O Stream
44/76
44
Line-Oriented I/O
Character I/O usually occurs in bigger units thansingle characters
One common unit is the line: a string of
characters with a line terminator at the end A line terminator can be a carriage-return/line-
feed sequence ("\r\n"), a single carriage-return("\r"), or a single line-feed ("\n").
-
8/14/2019 J21 Java I/O Stream
45/76
45
Example: Line-oriented I/O
File inputFile = new File("farrago.txt");File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);FileWriter out = new FileWriter(outputFile);
BufferedReader inputStream = new BufferedReader(in);PrintWriter outputStream = new PrintWriter(out);
String l;
while ((l = inputStream.readLine()) != null) {System.out.println(l);outputStream.println(l);
}
in.close();
-
8/14/2019 J21 Java I/O Stream
46/76
46
Buffered StreamBuffered Stream
Why Buffered Streams?
-
8/14/2019 J21 Java I/O Stream
47/76
47
Why Buffered Streams?
An unbuffered I/O means each read or write
request is handled directly by the underlying OS
This can make a program much less efficient, sinceeach such request often triggers disk access,network activity, or some other operation that is
relatively expensive. To reduce this kind of overhead, the Java platform
implements buffered I/O streams
Buffered input streams read data from a memory
area known as a buffer; the native input API is calledonly when the buffer is empty
Similarly, buffered output streams write data to abuffer, and the native output API is called only when
the buffer is full.
-
8/14/2019 J21 Java I/O Stream
48/76
48
How to create Buffered Streams?
A program can convert a unbuffered stream into abuffered stream using the wrapping idiom
A unbuffered stream object is passed to the constructor
for a buffered stream class Example
inputStream =
new BufferedReader(new FileReader("xanadu.txt"));
outputStream =
new BufferedWriter(new FileWriter("characteroutput.txt"));
-
8/14/2019 J21 Java I/O Stream
49/76
49
Buffered Stream Classes
BufferedInputStream and BufferedOutputStreamcreate buffered byte streams
BufferedReaderand BufferedWritercreate buffered
character streams
-
8/14/2019 J21 Java I/O Stream
50/76
50
Flushing Buffered Streams
It often makes sense to write out a buffer at criticalpoints, without waiting for it to fill. This is known asflushing the buffer.
Some buffered output classes support autoflush,
specified by an optional constructor argument.
When autoflush is enabled, certain key events causethe buffer to be flushed
For example, an autoflush PrintWriter object flushesthe buffer on every invocation of println or format.
To flush a stream manually, invoke its flush method
The flush method is valid on any output stream, but
has no effect unless the stream is buffered.
-
8/14/2019 J21 Java I/O Stream
51/76
51
Standard StreamsStandard Streams
-
8/14/2019 J21 Java I/O Stream
52/76
52
Standard Streams on Java Platform
Three standard streams
Standard Input, accessed through System.in
Standard Output, accessed through System.out
Standard Error, accessed through System.err
These objects are defined automatically and do notneed to be opened
System.out and System.err are defined asPrintStream objects
-
8/14/2019 J21 Java I/O Stream
53/76
53
Data StreamsData Streams
-
8/14/2019 J21 Java I/O Stream
54/76
54
Data Streams
Data streams support binary I/O of primitive datatype values (boolean, char, byte, short, int, long,float, and double) as well as String values
All data streams implement either the DataInputinterface or the DataOutput interface
DataInputStream and DataOutputStream are mostwidely-used implementations of these interfaces
-
8/14/2019 J21 Java I/O Stream
55/76
55
DataOutputStream
DataOutputStream can only be created as a wrapperfor an existing byte stream object
out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(dataFile)));
for (int i = 0; i < prices.length; i ++) {
out.writeDouble(prices[i]);
out.writeInt(units[i]);out.writeUTF(descs[i]);
}
DataInputStream
-
8/14/2019 J21 Java I/O Stream
56/76
56
DataInputStream Like DataOutputStream, DataInputStream must be
constructed as a wrapper for a byte stream
End-of-file condition is detected by catchingEOFException, instead of testing for an invalid returnvalue
in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
try{double price = in.readDouble();int unit = in.readInt();String desc = in.readUTF();
} catch (EOFException e){}
-
8/14/2019 J21 Java I/O Stream
57/76
57
Object StreamsObject Streams
Obj t St
-
8/14/2019 J21 Java I/O Stream
58/76
58
Object Streams
Object streams support I/O of objects
Like Data streams support I/O of primitive data types
The object has to be Serializable type
The object stream classes are ObjectInputStreamand ObjectOutputStream
These classes implement ObjectInput andObjectOutput, which are subinterfaces of DataInput
and DataOutput An object stream can contain a mixture of primitive
and object values
Input and Output of Complex
-
8/14/2019 J21 Java I/O Stream
59/76
59
Input and Output of ComplexObject
The writeObject and readObject methods aresimple to use, but they contain some verysophisticated object management logic
This isn't important for a class like Calendar, whichjust encapsulates primitive values. But many objectscontain references to other objects.
If readObject is to reconstitute an object from astream, it has to be able to reconstitute all of theobjects the original object referred to.
These additional objects might have their ownreferences, and so on.
W it Obj t
-
8/14/2019 J21 Java I/O Stream
60/76
60
WriteObject
The writeObject traverses the entire web of objectreferences and writes all objects in that web ontothe stream
A single invocation of writeObject can cause a largenumber of objects to be written to the stream.
-
8/14/2019 J21 Java I/O Stream
61/76
I/O f lti l f d t bj t
-
8/14/2019 J21 Java I/O Stream
62/76
62
I/O of multiple referred-to objects
Invoking writeObject(a) writes not just a, but all theobjects necessary to reconstitute a, so the otherfour objects in this web are written also
When a is read back by readObject, the other fourobjects are read back as well, and all the originalobject references are preserved.
-
8/14/2019 J21 Java I/O Stream
63/76
63
Closing StreamsClosing Streams
Always Close Streams
-
8/14/2019 J21 Java I/O Stream
64/76
64
Always Close Streams
Closing a stream when it's no longer needed is veryimportant so important that your program shoulduse a finally block to guarantee that both streamswill be closed even if an error occurs
This practice helps avoid serious resource leaks.
-
8/14/2019 J21 Java I/O Stream
65/76
65
File ClassFile Class
The File Class
-
8/14/2019 J21 Java I/O Stream
66/76
66
The File Class
Not a stream class
Important since stream classes manipulate Fileobjects
Abstract representation of actual files and directorypathname
The File Class: Constructors
-
8/14/2019 J21 Java I/O Stream
67/76
67
The File Class: Constructors
Has four constructors
The File Class: Methods
-
8/14/2019 J21 Java I/O Stream
68/76
68
The File Class: Methods
The File Class: Methods
-
8/14/2019 J21 Java I/O Stream
69/76
69
The File Class: Methods
The File Class: Example
-
8/14/2019 J21 Java I/O Stream
70/76
70
The File Class: Example
1 import java.io.*;
2
3 public class FileInfoClass {
4 public static void main(String args[]) {
5 String fileName = args[0];
6 File fn = new File(fileName);
7 System.out.println("Name: " + fn.getName());
8 if (!fn.exists()) {
9 System.out.println(fileName
10 + " does not exists.");
11 //continued...
The File Class: Example
-
8/14/2019 J21 Java I/O Stream
71/76
71
The File Class: Example
12 /* Create a temporary directory instead. */
13 System.out.println("Creating temp directory...");
14 fileName = "temp";
15 fn = new File(fileName);
16 fn.mkdir();
17 System.out.println(fileName +
18 (fn.exists()? "exists": "does not exist"));
19 System.out.println("Deleting temp directory...");
20 fn.delete();
21 //continued...
The File Class: Example
-
8/14/2019 J21 Java I/O Stream
72/76
72
The File Class: Example
24
25 System.out.println(fileName + " is a " +
26 (fn.isFile()? "file." :"directory."));
27
28 if (fn.isDirectory()) {
29 String content[] = fn.list();
30 System.out.println("The content of this directory
43 for (int i = 0; i < content.length; i++) {
44 System.out.println(content[i]);45 }
46 }
35
36
//continued...
The File Class: Example
-
8/14/2019 J21 Java I/O Stream
73/76
73
The File Class: Example
36
37
38 if (!fn.canRead()) {
39 System.out.println(fileName
40 + " is not readable.");
41 return;
42 }
43 //continued...
The File Class: Example
-
8/14/2019 J21 Java I/O Stream
74/76
74
The File Class: Example
47 System.out.println(fileName + " is " + fn.length()
48 + " bytes long.");
49 System.out.println(fileName + " is " +
50 fn.lastModified() + " bytes long.");
51
52 if (!fn.canWrite()) {
53 System.out.println(fileName
54 + " is not writable.");
55 }56 }
57 }
Modified InputStream/O t tSt E l
-
8/14/2019 J21 Java I/O Stream
75/76
75
OutputStream Example24 } catch (IOException ie) {
25 ie.printStackTrace();
26 }
27 }
28
29 public static void main(String args[]) {
30 String inputFile = args[0];
31 CopyFile cf = new CopyFile();
32 cf.copy(inputFile);
33 }
34 }
-
8/14/2019 J21 Java I/O Stream
76/76
76
Thank You!Thank You!