Object Input/Output - PowerPoint PPT Presentation

1 / 11
About This Presentation
Title:

Object Input/Output

Description:

Object Input/Output Object I/O To write objects to a file, we use ObjectOutputStream To read objects from a file we use ObjectInputStream Lets see how we write Person ... – PowerPoint PPT presentation

Number of Views:126
Avg rating:3.0/5.0
Slides: 12
Provided by: PORe151
Category:
Tags: input | object | output

less

Transcript and Presenter's Notes

Title: Object Input/Output


1
Object Input/Output
2
Object I/O
  • To write objects to a file, we use
    ObjectOutputStream
  • To read objects from a file we use
    ObjectInputStream
  • Lets see how we write Person objects to a file
  • First we need to modify the definition of the
    Person class in order to perform object I/O

3
Object I/O
  • If you want to perform an object I/O, then the
    class definition must include the phrase
    implements Serializable
  • import java.io.
  • class person implements Serializable
  • // the rest is the same

4
Object I/O
  • If a class is a subclass, then the class
    definition must also change.

5
Object I/O
  • You need File, FileInputStream, ObjectInputStream
    FileOutputStream, and ObjectOutputStream objects
    to do object I/O.
  • To write a Person object to a file, we first
    create an ObjectOutputStream object

6
Object I/O
File outFile new File ("objects.
txt") FileOutputStream outFileStream new
FileOutputStream (outFile) ObjectOutputStream
outObjectStream new ObjectOutputStream
(outFileStream) To save a Person object, we
write Person person new Person ("mR.
eXPRESSO", 20, 'm') OutObjectStream.writeObject
(person)
7
It is possible to save different types of objects
to a single file. Assuming the Account and Bank
classes are defined properly, we can save both
types of objects to a single file Account
account 1, account 2 Bank bank1,
bank2 account1 new Account() account2 new
Account() bank 1 new Bank() bank2 new
Bank() outObjectStream.writeObject (account
1) outObjectStream.writeObject (account
2) outObjectStream.writeObject (bank
1) outObjectStream.writeObject (bank 2)
8
You can even mix objects and primitives! outObject
Stream.writeObject (account 1) outObjectStream.wr
iteInt (15)
9
Object I/O
  • To read objects from a file, we use
    FileInputStream and ObjectInputStream
  • We can use the method readObject to read an
    object.
  • Since we can store any type of objects to a
    single file, we need to cast the object read from
    the file.
  • Heres an example of reading a person object we
    saved in the file objects.data

10
Reading Objects
File inFile new File("objects.txt") FileInputSt
ream inFileStream new FileInputStream
(inFile) ObjectInputStream inObjectStream new
ObjectInputStream (inFileStream) Person person
(Person) inObjectStream.readObject()
11
See Handout Examples 1 and 2
Write a Comment
User Comments (0)
About PowerShow.com