03 Io1
03 Io1
IO
Session objectives
2
I/O stream
3
I/O Streams
4
I/O Streams
5
Types of Streams
6
General Stream Types
7
Character and Byte Streams
• Byte streams
o For binary data
o Root classes for byte streams:
• The InputStream Class
• The OutputStream Class
• Both classes are abstract
• Character streams
o For Unicode characters
o Root classes for character streams:
• The Reader class
• The Writer class
• Both classes are abstract
8
Input and Output Streams
9
Node and Filter Streams
11
Control Flow of an I/O operation
12
Byte Stream
13
Byte Stream
• They are used in much the same way; they differ mainly in the
way they are constructed
14
When Not to Use Byte Streams?
• Byte streams should only be used for the most primitive I/O
• All other streams are based on byte stream
15
Byte Stream example
16
Character Stream
17
Character Stream
18
Character Stream
19
Character Stream example
20
Character Stream and Byte Stream
21
Line-Oriented I/O
22
Line-Oriented I/O example
23
Buffered Stream
24
The necessary of Buffered Streams
26
Buffered Stream Classes - Reading demo
27
Buffered Stream Classes - Writing demo
28
Flushing Buffered Streams
30
Standard Streams on Java Platform
31
Data Streams
32
Data Streams
33
The DataOutputStream class
34
DataOutputStream demo
35
The DataInputStream class
36
The DataInputStream exemple
37
Object Streams
38
Object Serialization
39
Object Streams
40
Object Serialization
41
Object serialization demo
42
Output and Input of Complex Objects
43
I/O of multiple referred-to objects
44
NIO - New I/O
45
NIO.2 - New I/O version 2
• Socket/Channel construct
o Binding, options and multicast
46
NIO.2 - Path
• java.nio2.file.Path interface
o Typically represents a file on a file system
o normalize() method removes constructs such as . and .. in a Path
o relativize(Path) constructs relative Path between this path and the
one given
o Lots of other expected methods defined in the interface
o Dealing with real path, absolute path etc
o Can convert java.io.File objects via the toFile() method
• java.nio2.file.Paths
o Helper class, provides get(URI) method to return you a Path
o Uses FileSystems helper class under the hood
o Uses the default file system unless you specify otherwise
47
NIO.2 - Files
49
NIO.2 - Asynchronous I/O
• Is available for:
o file I/O (AsynchronousFileChannel)
o networking I/O (AsynchronousSocketChannel)
• And AsynchronousServerSocketChannel
• Can work in two styles
o Future based (order coffee, do something else, collect coffee)
o Callbacks (order coffee, do something else, have coffee thrown at
you)
50
NIO.2 - Future based file I/O example
51
NIO.2 - Callback based file I/O example
52
Summary
53
54