java io stream

Click here to load reader

Post on 28-Jan-2017




1 download

Embed Size (px)


  • 1

    Java IO Stream

  • 2

    Ni dung

    Lung nhp xut l g? Cc loi lung Phn cp lp lung Dng Stream iu khin lung nhp xut. Byte streams

    Character streams Buffered streams

    Standard I/O streams Data streams Object streams

    Lp File

  • 3

    Khi nim lung?

    Lung l mt dng chy ca d liu c gn vicc thit b vo ra.

    Hai loi lung: Lung nhp: Gn vi cc thit b nhp nh bn phm, my

    scan, file...

    Lung xut: Gn vi cc thit b xut nh mn hnh, myin, file...

    Vic x l vo ra thng qua lung gip cho lp trnhvin khng phi quan tm n bn cht ca thit bvo ra.

  • 4

    Input Stream

    Chng trnh s dng input stream cd liu t ngun.

  • 5

    Output Stream

    Chng trnh s dng output stream ghid liu xung ch.

  • 6

    Cc loi lung

    Character and Byte Streams

    Character vs. Byte

    Input and Output Streams

    Da trn ngun v ch

    Node and Filter Streams

    Khi d liu trong lung c thao tc hocchuyn i.

  • 7

    Character and Byte Streams

    Byte streams Cho d liu dng nh phn Nhng lp gc cho cc byte stream:

    Lp InputStream Lp OutputStream C 2 lp l tru tng (Abstract)

    Character streams Cho cc k t Unicode Nhng lp gc cho character stream:

    Lp Reader Lp Writer C 2 lp l tru tng (Abstract)

  • 8

    Input and Output Streams

    Input or source streams C th c t nhng ngun ny. Nhng lp gc ca tt c cc input stream:

    Lp InputStream Lp Reader

    Output or destination streams C th ghi xung nhng lung ny Nhng lp gc ca tt c cc output stream:

    Lp OutputStream Lp Writer

  • 9

    Node and Filter Streams

    Node streams (Data sink stream) Cha nhng chc nng c bn cho vic c v ghi t mt

    v tr xc nh. Cc loi node stream bao gm file, b nh v pipe

    Filter streams (Processing stream) Lung lc c kh nng kt ni vi cc lung khc v x l

    d liu theo cch ring ca n. FilterInputStream v FilterOutputStream l 2 lp lung lc

    c bn.

  • 10

    Hierarchy of classes and interfacesObject

    File FileDescriptor

    RandomAccessFileDataInput DataOutput
















  • 11

    Hierarchy of classes and interfacesObject



















  • 12

    Abstract Classes

    InputStream & OutputStream

    Reader & Writer

  • 13

    InputStream Abstract Class public abstract int read() throws IOException

    c mt byte k tip ca d liu t lung.

    public int read(byte[] bBuf) throws IOException

    c mt s byte d liu t lung v lu vo mng byte bBuf.

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

    c length byte d liu t lung v lu vo mng byte cBuf bt u ti vtr offset.

    public void close() throws IOException

    ng ngun. Gi nhng phng thc khc sau khi ngun s gy ra liIOException

    public int mark(int readAheadLimit) throws IOException

    nh du v tr hin hnh ca stream. Sau khi nh du, gi reset() snh li v tr ca lung n im ny. Khng phi tt c lung byte input htr cho thao tc ny.

    public int markSupported()

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

  • 14

    Node InputStream Classes


    c cc byte t file


    Thc thi mt buffer m n cha cc byte, m n c thc c t ngun.


    Nn c lin kt vi PipedOutputStream. Nhnglung ny c s dng bi 2 lung. Trong mt ci lc d liu t ngun trong khi nhng ci khc th ghixung PipedOutputStream tng ng.

  • 15

    Filter InputStream Classes


    Mt class con ca FilterInputStream cho php t vng m cho input c cc byte d liu mt cch hiu qu.


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


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


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


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


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

  • 16

    Lp tru tng OutputStream public void write(int b) throws IOException

    Ghi gi tr b xc nh theo dng byte xung output stream

    public void write(byte[] b) throws IOException

    Lu ni dung ca mng byte b xung lung

    public void write(byte[] b, int off, int len) throws IOException

    Lu len byte ca mng byte b xung lung, bt u t v tr off ca mng

    public void close() throws IOException

    ng ngun. Gi nhng phng thc khc lin quan n ngun ny sau khi giclose se gy ra li IOException.

    public void flush() throws IOException

    flushes the stream.(v d: Nhng byte c lu trong buffer ngay lp tc cghi xung ch)

  • 17

    Node OutputStream Classes


    For writing bytes to a file


    Implements a buffer that contains bytes, which may be

    written to the stream


    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.

  • 18

    Filter OutputStream Classes


    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.


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


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


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


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

  • 19

    The Reader Class: Methods public int read() throws IOException

    c mt k t

    public int read(char[] cbuf) throws IOException

    c nhng k t v lu chng vo mng cbuf

    public abstract int read(char[] cbuf, int off, int len) throws IOException

    c len k t v lu chng vo tron mng cbuf, bt u ti v tr off ca mng

    public abstract void close() throws IOException

    ng lung. Gi nhng phng thc Reader khc ca sau khi gi close s gy ra li IOException

    public void mark(int readAheadLimit) throws IOException

    nh du v tr hin hnh ca stream. Sau khi nh du, gi reset() th t li v tr lung tiim ny. Khng phi tt c character-input u h tr thao tc ny

    public boolean markSupported()

    Ch ra lung c h tr thao tc ny hay khng. Mc nh l khng h tr.

    public void reset() throws IOException

    t li v tr lung ti v tr nh du ln cui

  • 20

    Node Reader Classes


    Cho vic c t file


    Thc thi mt vng m k t c th c c


    Cho vic c t ngun string


    Dng theo cp (tng ng vi PipedWriter) bng2 lung m chng c th lin lc vi nhau.Mttrong nhng ci lung c cc k t.

  • 21

    Filter Reader Classes BufferedReader

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


    For reading filtered character streams


    Converts read bytes to characters


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


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

  • 22

    The Writer Class: Methods

    public void write(int c) throws IOException

    Ghi mt k t n c th hin bng s nguyn. V d: A l c ghi la write(65)

    public void write(char[] cbuf) throws IOException

    Ghi ni dung ca mng k t cbuf xung lung public abstract void write(char[] cbuf, int off, int len)

    throws IOException

    Ghi mt mng k t cbuf vi chiu di l len, bt u l v tr off public void write(String str) throws IOException

    Ghi mt chui str public void write(String str, int off, int len) throws


    Ghi mt chui str vi chiu di l len, bt u t v tr off public abstract void flush() throws IOException

    y d liu xung ch n. public abstract void close() throws IOException

    ng lung.

  • 23

    Node Writer Classes


    For writing to character to file


    Implements a character buffer that can be written to


    For writing to a string source


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

  • 24

    Filter Writer Classes


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


    For writing filtered character streams.


    Encodes characters written to it into bytes.


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

  • 25

    iu khin lung nhp xut(I/O)

    To i tng lung v lin kt n vi d liungun(data-destination)

    a ra i tng lung vi chc nng mongmun thng qua chui lung (Give the stream object the desired functionality

    through stream chaining)

    ng lung

  • 26

    Byte Stream

    Chng trnh s dng lung byte thchin nhp xut nhng byte 8-bit

    Tt c c lp lung byte c k tha tInputStream v OutputStream

    C nhiu lp lung byte FileInputStream v FileOutputStream

    Chng c s dng trong cng mt cch; chng khc nhau ch yu l cch thc chngc khi to.

  • 27

    Khi no khng s dng Byte Stream

    Byte Stream th hin mt loi d liu nhpxut mc thp do chng ta nn trnh: Nu d liu cha nhng k t, phng php tt

    nht l s dng character streams C nhng stream cho nhng kiu d liu phc


    Byte Stream ch nn s dng cho hu htnhng nhp xut nguyn thy

    Tt c cc stream khc u c da trnbyte stream

  • 28

    Example: FileInputStream &


    import*;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 = != -1) { out.write(c); }

    }finally {

    if (in != null) { in.close(); }if (out != null) { out.close(); }



  • 29

    Simple Byte Stream input and


    b = read()


    H e l l o Y

    H e l l o oY u




  • 30

    Character Stream

    Java platform lu tr nhng gi tr k t theodng Unicode

    Tt c cc lp character stream c k that Reader v Writer

    C cc lp character stream : FileReader vFileWriter.

  • 31

    Example: FileReader &


    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 = != -1) { outputStream.write(c);}

    }finally {

    if (inputStream != null) { inputStream.close(); }if (outputStream != null) { outputStream.close(); }



  • 32

    Character Stream v Byte Stream

    Character stream thng l "wrappers chobyte stream

    Character stream s dng byte stream thchin nhp xut vt l, trong khi character stream x l chuyn i gia character vbyte

    Chng hn FileReader dng nhFileInputStream, trong khi FileWriter dng nhFileOutputStream

  • 33

    Buffered Streams

    Mt I/O khng c b m c ngha l mi yu cuc hoc ghi c x l trc tip bi OS iu ny lm chng trnh km hiu qu, v mi yu cu

    thng phi truy xut a, hot ng mng, hoc mt vthao tc kh m n tng i tn thi gian.

    gim cng vic loi ny, Java platform thc thilung I/O c b m Buffered input stream c d liu t vng nh nh l b

    m; API input c gi ch khi b m rng.

    Tng t, buffered output stream ghi d liu xung bm, v API output ch c gi khi buffer y.

  • 34

    To Buffered Stream?

    Mt chng trnh c th chuyn mt stream khng c b m thnh stream c b mbng cch s dng v bao. Mt unbuffered stream object c chuyn qua

    hm dng cho mt lp stream c b m

    V d:inputStream = new BufferedReader(new


    outputStream = new BufferedWriter(new


  • 35

    Buffered Stream Classes

    BufferedInputStream v

    BufferedOutputStream to ra byte stream c b m

    BufferedReader v BufferedWriter tora character stream c b m

  • 36

    Standard Streams on Java


    C 3 standard stream


    Output: System.out

    Error: System.err

    Nhng i tng ny c nh ngha tng v khng cn thit c m.

    System.out and System.err c nh nghanh l nhng PrintStream object

  • 37

    Data Streams

    Data stream h tr nhp xut nh phn ca cc loid liu nguyn thu (boolean, char, byte, short, int, long, float, and double) cng nh l String

    Tt c data stream thc thi c DataInput cngnh DataOutput interface

    DataInputStream and DataOutputStream thcthi nhng phng thc ca nhng interface ny

  • 38


    DataOutputStream c th ch c to nh l mv bc cho i tng byte stream

    out = new DataOutputStream(

    new BufferedOutputStream(

    new FileOutputStream(dataFile)));

    for (int i = 0; i < prices.length; i ++) {





  • 39


    Ging nh DataOutputStream, DataInputStream phi c xydng nh l mt v bc cho i tng byte stream

    iu kin End-of-file c d bi bit l EOFException, thay vkim tra tr v gi tr ht file.

    in = new DataInputStream(new BufferedInputStream(

    new FileInputStream(dataFile)));


    double price = in.readDouble();

    int unit = in.readInt();

    String desc = in.readUTF();

    } catch (EOFException e){


  • 40

    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

  • 41

    Input and Output of Complex


    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.

  • 42


    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


  • 43

    I/O of multiple referred-to objects

    Object a contains references to objects b and

    c, while b contains references to d and e

  • 44

    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


    When a is read back by readObject, the other

    four objects are read back as well, and all the

    original object references are preserved.

  • 45

    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.

  • 46

    The File Class

    Not a stream class

    Important since stream classes manipulate

    File objects

    Abstract representation of actual files and

    directory pathname

  • 47

    The File Class: Constructor &


    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()

  • 48

    The File Class: Example


    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);


    System.out.println(fileName + (fn.exists()? "exists": "does not exist"));

    System.out.println("Deleting temp directory...");



  • 49

    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++)



    if (!fn.canRead()) {

    System.out.println(fileName + " is not readable.");



    System.out.println(fileName + " is " + fn.length() + " bytes long.");

    System.out.println(fileName + " is " + fn.lastModified()

    + " byteslong.");

    if (!fn.canWrite()) {

    System.out.println(fileName + " is not writable.");