Você está na página 1de 49

Java IO Stream

N i dung
Lu ng nh p xu t l g? Cc lo i lu ng Phn c p l p lu ng Dng Stream i u khi n lu ng nh p xu t. Byte streams Character streams Buffered streams Standard I/O streams Data streams Object streams L p File
2

Khi ni m lu ng?
Lu ng l m t dng ch y c a d li u c g n v i cc thi t b vo ra. Hai lo i lu ng:
Lu ng nh p: G n v i cc thi t b nh p nh bn phm, my scan, file... Lu ng xu t: G n v i cc thi t b xu t nh mn hnh, my in, file...

Vi c x l vo ra thng qua lu ng gip cho l p trnh vin khng ph i quan tm n b n ch t c a thi t b vo ra.
3

Input Stream
Chng trnh s d ng input stream c d li u t ngu n.

Output Stream
Chng trnh s d ng output stream ghi d li u xu ng ch.

Cc lo i lu ng
Character and Byte Streams
Character vs. Byte

Input and Output Streams


D a trn ngu n v ch

Node and Filter Streams


Khi d li u trong lu ng c thao tc ho c chuy n i.

Character and Byte Streams


Byte streams
Cho d li u d ng nh phn Nh ng l p g c cho cc byte stream: L p InputStream L p OutputStream C 2 l p l tr u t ng (Abstract)

Character streams
Cho cc k t Unicode Nh ng l p g c cho character stream: L p Reader L p Writer C 2 l p l tr u t ng (Abstract)
7

Input and Output Streams


Input or source streams
C th c t nh ng ngu n ny. Nh ng l p g c c a t t c cc input stream:
L p InputStream L p Reader

Output or destination streams


C th ghi xu ng nh ng lu ng ny Nh ng l p g c c a t t c cc output stream:
L p OutputStream L p Writer
8

Node and Filter Streams


Node streams (Data sink stream)
Ch a nh ng ch c nng c b n cho vi c c v ghi t m t v tr xc nh. Cc lo i node stream bao g m file, b nh v pipe

Filter streams (Processing stream)


Lu ng l c c kh nng k t n i v i cc lu ng khc v x l d li u theo cch ring c a n. FilterInputStream v FilterOutputStream l 2 l p lu ng l c c b n.

Hierarchy of classes and interfaces


File DataInput InputStream ByteArray InputStream DataInput Stream FileInput Stream Filter InputStream FileOutput Stream Object RandomAccessFile FileDescriptor DataOutput OutputStream Filter OutputStream ByteArray OutputStream

Buffered InputStream

LineNumber InputStream

PushBack InputStream Buffered OutputStream

DataOutput Stream Print Stream


10

Hierarchy of classes and interfaces Object


Reader Buffered Reader Filter Reader Piped Reader String Reader Buffered Writer CharArray Writer Writer Filter Writer Piped Writer String Writer Print Writer

CharArray Reader

InputStream Reader

OutputStream Writer

LineNumberReader

FileReader PushbackReader

Print Stream
11

Abstract Classes
InputStream & OutputStream Reader & Writer

12

InputStream Abstract Class


public abstract int read() throws IOException

c m t byte k ti p c a d li u t lu ng.
public int read(byte[] bBuf) throws IOException

c m t s byte d li u t lu ng v lu vo m ng byte bBuf.


public int read(byte[] cBuf, int offset, int length) throws IOException

c length byte d li u t lu ng v lu vo m ng byte cBuf b t u t i v tr offset.


public void close() throws IOException

ng ngu n. G i nh ng phng th c khc sau khi ngu n s gy ra l i IOException


public int mark(int readAheadLimit) throws IOException

nh d u v tr hi n hnh c a stream. Sau khi nh d u, g i reset() s nh l i v tr c a lu ng n i m ny. Khng ph i t t c lu ng byte input h tr cho thao tc ny.
public int markSupported()

Ch ra lu ng c h tr thao tc mark v reset hay khng


13

Node InputStream Classes


FileInputStream
c cc byte t file

ByteArrayInputStream
Th c thi m t buffer m n ch a cc byte, m n c th c c t ngu n.

PipedInputStream
Nn c lin k t v i PipedOutputStream. Nh ng lu ng ny c s d ng b i 2 lu ng. Trong m t ci l c d li u t ngu n trong khi nh ng ci khc th ghi xu ng PipedOutputStream tng ng.
14

Filter InputStream Classes


BufferedInputStream
M t class con c a FilterInputStream cho php t vng m cho input c cc byte d li u m t cch hi u qu .

FilterInputStream
For reading filtered byte streams, which may transform the basic source data along the way and provide additional functionalities.

ObjectInputStream
Used for object serialization. Deserializes objects and previuosly written using an ObjectOutputStream.

DataInputStream
A subclass of FilterInputStream that lets an application read Java primitive data from underlying inputstream in a machine-independent way.

LineNumberInputStream
A subclass of FilterInputStream that allows tracking of the current line number.

PushbackInputStream
A subclass of FilterInputStream class that allows bytes to be pushed back or unread into the stream
15

L p tr u t ng OutputStream
public void write(int b) throws IOException Ghi gi tr b xc nh theo d ng byte xu ng output stream public void write(byte[] b) throws IOException Lu n i dung c a m ng byte b xu ng lu ng public void write(byte[] b, int off, int len) throws IOException Lu len byte c a m ng byte b xu ng lu ng, b t u t v tr off c a m ng public void close() throws IOException ng ngu n. G i nh ng phng th c khc lin quan n ngu n ny sau khi g i close se gy ra l i IOException. public void flush() throws IOException flushes the stream.(v d : Nh ng byte c lu trong buffer ngay l p t c c ghi xu ng ch)
16

Node OutputStream Classes


FileOuputStream
For writing bytes to a file

ByteArrayOutputStream
Implements a buffer that contains bytes, which may be written to the stream

PipedOutputStream
Should be connected to a PipedInputStream. These streams are typically used by two threads wherein one of these threads writes data to this stream while the other thread reads from the corresponding PipeInputStream.
17

Filter OutputStream Classes


BufferedOutputStream
A subclass of FilterOutputStream that allows buffering of output in order to provide for the efficient writing of bytes. Allows writing of bytes to the underlying output stream without necessarily causing a call to underlying system for each byte written.

FilterOutputStream
For writing filtered byte streams, which may transform the basic source of data along the way and provide additional functionalities.

ObjectOutputStream
Used for object serialization. Serializes object and primitve data to OuputStream.

DataOutputStream
A subclass of FilterOutputStream that lets an application write Java primitive data to underlying output stream in machine-independent way.

PrintStream
A subclass of FilteOutputStream that provides capability for printing representations of various data values conveniently.
18

The Reader Class: Methods


public int read() throws IOException
c m t k t

public int read(char[] cbuf) throws IOException


c nh ng k t v lu chng vo m ng cbuf

public abstract int read(char[] cbuf, int off, int len) throws IOException
c len k t v lu chng vo tron m ng cbuf, b t u t i v tr off c a m ng

public abstract void close() throws IOException


ng lu ng. G i nh ng phng th c Reader khc c a sau khi g i close s gy ra l i IOException

public void mark(int readAheadLimit) throws IOException


nh d u v tr hi n hnh c a stream. Sau khi nh d u, g i reset() th t l i v tr lu ng t i i m ny. Khng ph i t t c character-input u h tr thao tc ny

public boolean markSupported()


Ch ra lu ng c h tr thao tc ny hay khng. M c nh l khng h tr .

public void reset() throws IOException


t l i v tr lu ng t i v tr nh d u l n cu i
19

Node Reader Classes


FileReader
Cho vi c c t file

CharArrayReader
Th c thi m t vng m k t c th c c

StringReader
Cho vi c c t ngu n string

PipedReader
Dng theo c p (tng ng v i PipedWriter) b ng 2 lu ng m chng c th lin l c v i nhau.M t trong nh ng ci lu ng c cc k t .
20

Filter Reader Classes BufferedReader


Allows buffering of characters in order to provide for efficient reading of characters, arrays, and lines

FilterReader
For reading filtered character streams

InputStreamReader
Converts read bytes to characters

LineNumberReader
A subclass of BufferedReader class that able to keep track of line numbers.

PushbackReader
A subclass of the FilterReader class that allows character to pushed back or unread into the stream.
21

The Writer Class: Methods


public void write(int c) throws IOException Ghi m t k t n c th hi n b ng s nguyn. V d : A l c ghi la write(65) public void write(char[] cbuf) throws IOException Ghi n i dung c a m ng k t cbuf xu ng lu ng public abstract void write(char[] cbuf, int off, int len) throws IOException Ghi m t m ng k t cbuf v i chi u di l len, b t u l v tr off public void write(String str) throws IOException Ghi m t chu i str public void write(String str, int off, int len) throws IOException Ghi m t chu i str v i chi u di l len, b t u t v tr off public abstract void flush() throws IOException y d li u xu ng ch n. public abstract void close() throws IOException ng lu ng.
22

Node Writer Classes


FileWriter
For writing to character to file

CharArrayWriter
Implements a character buffer that can be written to

StringWriter
For writing to a string source

PipedWriter
Used in pairs(with corresponding with PipedReader) by two threads that want to communicate. One of these threads writes characters to this stream.
23

Filter Writer Classes


BufferedWriter
Allows buffering of characters in order to provide for the efficient writing of characters, arrays, and lines.

FilterWriter
For writing filtered character streams.

OutputStreamWriter
Encodes characters written to it into bytes.

PrintWriter
Prints formatted representations of objects to a text-output stream.
24

i u khi n lu ng nh p xu t(I/O)
T o i t ng lu ng v lin k t n v i d li u ngu n(data-destination) a ra i t ng lu ng v i ch c nng mong mu n thng qua chu i lu ng (Give the stream object the desired functionality through stream chaining) ng lu ng
25

Byte Stream
Chng trnh s d ng lu ng byte th c hi n nh p xu t nh ng byte 8-bit T t c c l p lu ng byte c k th a t InputStream v OutputStream C nhi u l p lu ng byte
FileInputStream v FileOutputStream

Chng c s d ng trong cng m t cch; chng khc nhau ch y u l cch th c chng c kh i t o.


26

Khi no khng s d ng Byte Stream


Byte Stream th hi n m t lo i d li u nh p xu t m c th p do chng ta nn trnh:
N u d li u ch a nh ng k t , phng php t t nh t l s d ng character streams C nh ng stream cho nh ng ki u d li u ph c t p

Byte Stream ch nn s d ng cho h u h t nh ng nh p xu t nguyn th y T t c cc stream khc u c d a trn byte stream


27

Example: FileInputStream & FileOutputStream


import java.io.*; public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(d:/src.txt"); out = new FileOutputStream(d:/dst.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
28

Simple Byte Stream input and output


InputStream
H e l l o Y o u

b = read()

write(b)

OutputStream
29

Character Stream
Java platform lu tr nh ng gi tr k t theo d ng Unicode T t c cc l p character stream c k th a t Reader v Writer C cc l p character stream : FileReader v FileWriter.

30

Example: FileReader & FileWriter


public class CopyCharacters { public static void main(String[] args) throws IOException { FileReader inputStream = null; FileWriter outputStream = null; try { inputStream = new FileReader(d:/fileIn.txt"); outputStream = new FileWriter(d:/fileOut.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c);} } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } }
31

Character Stream v Byte Stream


Character stream th ng l "wrappers cho byte stream Character stream s d ng byte stream th c hi n nh p xu t v t l, trong khi character stream x l chuy n i gi a character v byte
Ch ng h n FileReader dng nh FileInputStream, trong khi FileWriter dng nh FileOutputStream
32

Buffered Streams
M t I/O khng c b m c ngha l m i yu c u c ho c ghi c x l tr c ti p b i OS
i u ny lm chng trnh km hi u qu , v m i yu c u th ng ph i truy xu t a, ho t ng m ng, ho c m t v thao tc kh m n tng i t n th i gian.

gi m cng vi c lo i ny, Java platform th c thi lu ng I/O c b m


Buffered input stream c d li u t vng nh nh l b m; API input c g i ch khi b m r ng. Tng t , buffered output stream ghi d li u xu ng b m, v API output ch c g i khi buffer y.
33

T o Buffered Stream?
M t chng trnh c th chuy n m t stream khng c b m thnh stream c b m b ng cch s d ng v bao.
M t unbuffered stream object c chuy n qua hm d ng cho m t l p stream c b m

V d :
inputStream = new BufferedReader(new FileReader("characterinput.txt")); outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
34

Buffered Stream Classes


BufferedInputStream v BufferedOutputStream t o ra byte stream c b m BufferedReader v BufferedWriter t o ra character stream c b m

35

Standard Streams on Java Platform


C 3 standard stream
Input: System.in Output: System.out Error: System.err

Nh ng i t ng ny c nh ngha t ng v khng c n thi t c m . System.out and System.err c nh ngha nh l nh ng PrintStream object


36

Data Streams
Data stream h tr nh p xu t nh phn c a cc lo i d li u nguyn thu (boolean, char, byte, short, int, long, float, and double) cng nh l String T t c data stream th c thi c DataInput cng nh DataOutput interface DataInputStream and DataOutputStream th c thi nh ng phng th c c a nh ng interface ny
37

DataOutputStream
DataOutputStream c th ch c t o nh l m v b c cho i t ng byte stream
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]); }
38

DataInputStream
Gi ng nh DataOutputStream, DataInputStream ph i c xy d ng nh l m t v b c cho i t ng byte stream i u ki n End-of-file c d b i bi t l EOFException, thay v ki m tra tr v gi tr h t file. in = new DataInputStream(new BufferedInputStream( new FileInputStream(dataFile))); try{ double price = in.readDouble(); int unit = in.readInt(); String desc = in.readUTF(); } catch (EOFException e){ }
39

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 ObjectInputStream and ObjectOutputStream


These classes implement ObjectInput and ObjectOutput, which are subinterfaces of DataInput and DataOutput An object stream can contain a mixture of primitive and object values

40

Input and Output of Complex Object


The writeObject and readObject methods are simple to use, but they contain some very sophisticated object management logic
This isn't important for a class like Calendar, which just encapsulates primitive values. But many objects contain references to other objects.

If readObject is to reconstitute an object from a stream, it has to be able to reconstitute all of the objects the original object referred to.
These additional objects might have their own references, and so on.
41

WriteObject
The writeObject traverses the entire web of object references and writes all objects in that web onto the stream A single invocation of writeObject can cause a large number of objects to be written to the stream.

42

I/O of multiple referred-to objects


Object a contains references to objects b and c, while b contains references to d and e

43

I/O of multiple referred-to objects


Invoking writeObject(a) writes not just a, but all the objects necessary to reconstitute a, so the other four objects in this web are written also When a is read back by readObject, the other four objects are read back as well, and all the original object references are preserved.

44

Always Close Streams


Closing a stream when it's no longer needed is very important so important that your program should use a finally block to guarantee that both streams will be closed even if an error occurs
This practice helps avoid serious resource leaks.

45

The File Class


Not a stream class Important since stream classes manipulate File objects Abstract representation of actual files and directory pathname

46

The File Class: Constructor & Methods


public File(String pathname) public String getName() public boolean exists() public long length() public long lastModified() public boolean canRead() public boolean canWrite() public boolean isFile() public boolean isDirectory() public String[] list() public boolean mkdir() public boolean delete()
47

The File Class: Example


import java.io.*; public class FileInfoClass { public static void main(String args[]) { String fileName = args[0]; File fn = new File(fileName); System.out.println("Name: " + fn.getName()); if (!fn.exists()) { System.out.println(fileName + " does not exists."); /* Create a temporary directory instead. */ System.out.println("Creating temp directory..."); fileName = "temp"; fn = new File(fileName); fn.mkdir(); System.out.println(fileName + (fn.exists()? "exists": "does not exist")); System.out.println("Deleting temp directory..."); fn.delete(); }
48

The File Class: Example


System.out.println(fileName + " is a " + (fn.isFile()? "file." :"directory.")); if (fn.isDirectory()) { String content[] = fn.list(); System.out.println("The content of this directory:"); for (int i = 0; i < content.length; i++) System.out.println(content[i]); } if (!fn.canRead()) { System.out.println(fileName + " is not readable."); return; } System.out.println(fileName + " is " + fn.length() + " bytes long."); System.out.println(fileName + " is " + fn.lastModified() + " bytes long."); if (!fn.canWrite()) { System.out.println(fileName + " is not writable."); } } }

49

Você também pode gostar