Download presentation
Presentation is loading. Please wait.
Published byAudra Hart Modified over 9 years ago
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 // 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! outObjectStream.writeObject (account 1); outObjectStream.writeInt (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"); FileInputStream inFileStream = new FileInputStream (inFile); ObjectInputStream inObjectStream = new ObjectInputStream (inFileStream); Person person = (Person) inObjectStream.readObject();
11
See Handout Examples 1 and 2
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.