lecture 6 streams and serialization

Upload: mina-fawzy

Post on 14-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Lecture 6 Streams and Serialization

    1/27

    Lecture 6Streams and Serialization

  • 7/27/2019 Lecture 6 Streams and Serialization

    2/27

    Stream Is essentially a sequence of bytes, representing a flow of data from a source

    to a destination.

    Source or destination could be for example disk file, device or networksocket.

  • 7/27/2019 Lecture 6 Streams and Serialization

    3/27

    Dealing with Streams

    Any read or write is performed in three simple steps:

    Step 1. Open the streamyou need to define some objects here

    Step 2. Until there is more data, keep reading in a read, or writing in a write.

    You need to use the methods of the objects defined in step1 to read the stream.

    Step 3. Close the stream.

  • 7/27/2019 Lecture 6 Streams and Serialization

    4/27

    Java IO Package

    The java.io package contains nearly every class you might ever need to performinput and output (I/O) in Java.

    All these streams represent an input source and an output destination.

    The stream in the java.io package supports many data such as primitives,

    Object, localized characters, etc.

  • 7/27/2019 Lecture 6 Streams and Serialization

    5/27

    Java IO Purposes and Features

    The Java IO classes, which mostly consists of readers / writers, are addressingvarious purposes. That is why there are so many different classes. The

    purposes addressed are summarized below:

    File Access

    Network Access

    Buffering

    Parsing

    Reading and Writing Text (Readers / Writers)

    Reading and Writing Primitive Data (long, int etc.)

    Reading and Writing Objects

  • 7/27/2019 Lecture 6 Streams and Serialization

    6/27

  • 7/27/2019 Lecture 6 Streams and Serialization

    7/27

    Input Streams

  • 7/27/2019 Lecture 6 Streams and Serialization

    8/27

    Reading text from the keyboard usingScanner class

    Step1: define a Scannerobject, sc or any name. To

    take input from the

    keyboard, use (System.in)

    Step2: use the Scannerobject to get data

    Step3: close the Scannerwhen finished using it!

    Import

    - java.util.* library thatincludes the Scanner class

  • 7/27/2019 Lecture 6 Streams and Serialization

    9/27

    Reading text from a file using Scanner class

    Import :

    - java.util.* to use Scanner class

    - java.io.* to use File class

    Step1a: create a File objectthat points to your text file.

    Step1b: define a Scannerobject, sc or any name. To

    take input from the text file,

    use the file object you

    created in Step2a

    Step2: use the Scannerobject to get data

    Step3: close the Scannerwhen finished using it!

  • 7/27/2019 Lecture 6 Streams and Serialization

    10/27

    Note

    for this code to work properly, we need to write

    some error handling code to handle the situationwhen the file is not found.

  • 7/27/2019 Lecture 6 Streams and Serialization

    11/27

    Common Scanner methods

    input methods:

    s = sc.next() Returns next token (i.e. "word).

    s = sc.nextLine() Returns an entire input line as a String.

    i = sc.nextInt() Returns next integer value.

    d = sc.nextDouble() Returns next double value.

    x = sc.nextXYZ() Returns value of type XYZ (primitive value if possible), whereXYZ is one of BigDecimal,BigInteger,Boolean,Byte,Float, or Short.

    test methods (used for error checking and loops):

    b = sc.hasNext() True if another token is available to be read.

    b = sc.hasNextLine() True if another line is available to be read.

    b = sc.hasNextInt() True if another int is available to be read.

    b = sc.hasNextDouble() True if another double is available to be read.

    b = sc.hasNextXYZ() XYZ stands for one of the input types available above.

  • 7/27/2019 Lecture 6 Streams and Serialization

    12/27

    Getting input using BufferedReader and another input stream reader

    The BufferedReaderwraps another Readerand improves performance.

    Readers:

    (1) InputStreamReaderto get input from keyb. as bytes and translates itto characters

    (2) FileReaderto get input from files.

    The BufferedReaderprovides a readLine method to read a line of text.

    Note that InputStreamReader

    doesnt provide areadLine method.

    Java also has a class called BufferedWriterthat has a similar function forwriting data.

  • 7/27/2019 Lecture 6 Streams and Serialization

    13/27

    Reading from keyboard Using Buffered

    Reader

    Step1: open aninput stream

    Step2: getdata

    Step3: closethe inputstream

    reading input from a File using FileReader

  • 7/27/2019 Lecture 6 Streams and Serialization

    14/27

    Reading from File Using Buffered Reader

    Step1: open aninput stream

    Step2: get data

    Step3: close theinput stream

    reading input from keyboard using InputStreamReader

  • 7/27/2019 Lecture 6 Streams and Serialization

    15/27

    Output Streams

  • 7/27/2019 Lecture 6 Streams and Serialization

    16/27

    Writing text to a file using PrintWriter class

    Step2: use the PrintWriter

    object to write text

    Step3: close the PrintWriterwhen finished using it!

    Import

    - java.io.* to use the

    PrintWriter class

    Step1b: create PrintWriterobject that points to your text

    file.

    Step1a: create a File objectthat points to your text file.

  • 7/27/2019 Lecture 6 Streams and Serialization

    17/27

    Note

    Any data in the aaa.txt file will be erased before writing thenew data using println method.

    For this code to work, we need to write some errorhandling code to handle the situation when the file is notfound.

    Solution

    Append Mode in File Writer

    FileWriter fw = new FileWriter(file, true);

    or

    PrintWriter out = new PrintWriter(new BufferedWriter(newFileWriter("outfilename", true)));

  • 7/27/2019 Lecture 6 Streams and Serialization

    18/27

    Summary

    SourceKeyboard, File,

    etc

    DestinationScreen, File, etc

    Classes to use

    Scanner

    BufferedReaderInputStreamReader

    FileReaderetc

    Classes to use

    PrintWriter

    BufferedWriterOutputStreamWrite

    FileWriteretc

  • 7/27/2019 Lecture 6 Streams and Serialization

    19/27

    SummaryREADING From Keyboard From File

    Scanner Scanner in = new Scanner(X);myString = in.next(); myInt = in.nextInt(); //etc

    in.close();

    Replace Xwith: System.in new File("C:/filename")

    BufferedReader BufferedReader in = new BufferedReader(X);myString = in.readLine();

    in.close();

    Replace Xwith: new InputStreamReader(System.in) new FileReader("C:/filename")

    WRITING To Screen To File

    PrintWriter PrintWriter out = new PrintWriter(X);out.println("some text here");out.close();

    Replace Xwith: System.out new File("C:/filename")

    BufferedWriter BufferedWriter out = new BufferedWriter(X);out.write(some text here");

    out.close();

    Replace Xwith: new outputStreamWriter(System.out) new FileWriter("C:/filename")

    OR instead of both classes, simply write:

    System.out.println(some text here);

  • 7/27/2019 Lecture 6 Streams and Serialization

    20/27

    For More About Other Input / Output stream Classes

    http://tutorials.jenkov.com/java-io/index.html

    http://tutorials.jenkov.com/java-io/index.htmlhttp://tutorials.jenkov.com/java-io/index.htmlhttp://tutorials.jenkov.com/java-io/index.htmlhttp://tutorials.jenkov.com/java-io/index.html
  • 7/27/2019 Lecture 6 Streams and Serialization

    21/27

    Exercise

    Develop a simple Employee Class with 3 methods (Save, Load and Print)

    Save method saves employee data to a file. The filename is passed to the method as a parameter

    Load method loads employee data from a file. The filename is passed to the method as a parameter

    Print Method prints employee data to the screen.

  • 7/27/2019 Lecture 6 Streams and Serialization

    22/27

    Serialization

  • 7/27/2019 Lecture 6 Streams and Serialization

    23/27

    Serializations and Deserialization

    Object serialization

    is the process of saving an object's state to a sequence ofbytes.

    Deserialization

    is the process of rebuilding those bytes into a live object.

  • 7/27/2019 Lecture 6 Streams and Serialization

    24/27

    How to Serialize an object

    1) To Serialize an object you must implement the serializable interface.

    implements Serializable

    {

    }

    2) Create output stream

    FileOutputStreamf= new FileOutputStream(filename);

    3) Create object output stream

    ObjectOutputStreamout = new ObjectOutputStream(f);

  • 7/27/2019 Lecture 6 Streams and Serialization

    25/27

    3-Serialize it

    out.writeObject(ObjectHere);

    4-close the stream

    out.close();

  • 7/27/2019 Lecture 6 Streams and Serialization

    26/27

    How to Deserialize Object

    1-create input stream

    FileinputStreamf= new FileinputStream(filename);

    2-create object input stream

    ObjectinputStreamin= new ObjectinputStream(f);

    3-DeSerialize it

    Object obj= in.readObject();

    4-Cast the object

    YourClassName x = (YourClassName ) obj;

    5-Close the stream.

    in.close();

  • 7/27/2019 Lecture 6 Streams and Serialization

    27/27

    END