Ввод - вывод. Сериализация

Содержание

Слайд 2

V. Ввод - вывод 5. Сериализация

V. Ввод - вывод
5. Сериализация


Слайд 3

Сериализация объектов

Сериализация объектов

Слайд 4

Маркерный интерфейс Serializable package java.io; public interface Serializable { } I

Маркерный интерфейс Serializable

package java.io;
public interface Serializable {
}

I

Слайд 5

Объектный поток вывода

Объектный поток вывода

Слайд 6

Класс ObjectOutputStream package java.io; public class ObjectOutputStream extends OutputStream implements ObjectOutput,

Класс ObjectOutputStream

package java.io;
public class ObjectOutputStream extends OutputStream implements ObjectOutput, ObjectStreamConstants{
public ObjectOutputStream(OutputStream out)
public void

writeObject(Object obj)
public void write(int b)
public void write(byte b[])
public void write(byte b[], int off, int len)
public final void writeBoolean(boolean v)
public final void writeByte(int v)
public final void writeShort(int v)
public final void writeChar(int v)
public final void writeInt(int v)
public final void writeLong(long v)
public final void writeFloat(float v)
public final void writeDouble(double v)
public final void writeBytes(String s)
public final void writeChars(String s)
public final void writeUTF(String str)
public void flush()
public void close()
}

C

public void writeObject(Object obj)

public ObjectOutputStream(OutputStream out)

Слайд 7

Объектный поток ввода

Объектный поток ввода

Слайд 8

Класс ObjectInputStream package java.io; public class ObjectInputStream extends InputStream implements ObjectInput,

Класс ObjectInputStream

package java.io;
public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants {

public ObjectInputStream(InputStream in)
public final Object readObject()
public int read()
public int read(byte b[], int off, int len)
public final boolean readBoolean()
public final byte readByte()
public final short readShort()
public final int readInt()
public final long readLong()
public final float readFloat()
public final double readDouble()
public final String readUTF()
}

public final Object readObject()

public ObjectInputStream(InputStream in)

C

Слайд 9

Сериализация и десериализация одного объекта


Сериализация и десериализация
одного объекта

Слайд 10

Сериализуемый класс class Employee implements Serializable { public Employee() { System.out.println("Employee

Сериализуемый класс

class Employee implements Serializable {
public Employee() {
System.out.println("Employee object

is being created using a default constructor");
}
public Employee(String name, short yearOfBirth, char gender,
boolean isMarried, int salary) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.gender = gender;
this.isMarried = isMarried;
this.salary = salary;
numEmployees++;
System.out.println("Employee object is being created using a constructor");
}
public String toString() {
return "Employee [name=" + name + ", yearOfBirth=" + yearOfBirth
+ ", gender=" + gender + ", isMarried=" + isMarried + ", salary="
+ salary + "]";
}
public static int getNumEmployees(){
return numEmployees;
}
private String name;
private short yearOfBirth;
private char gender;
private boolean isMarried;
private int salary;
private static int numEmployees = 0;
}
Слайд 11

Сериализация public class ObjectOutputDemo { public static void main(String[] args) {

Сериализация

public class ObjectOutputDemo {
public static void main(String[] args) {
Employee bob

= new Employee("Robert", (short) 1987, 'M', true, 30000);
System.out.println(bob);
System.out.println("Total number of employees: " + Employee.getNumEmployees());
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("I:\\FileIO\\employee.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(bob);
System.out.println("Employee object was serialized");
} catch (IOException e) {
System.out.println("An I/O error occured");
} finally {
try {
if (oos != null)
oos.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
Employee object is being created using a constructor
Employee [name=Robert, yearOfBirth=1987, gender=M, isMarried=true, salary=30000]
Total number of employees: 1
Employee object was serialized

Total number of employees: 1

Employee object is being created using a constructor

Слайд 12

Десериализация class ObjectInputDemo { public static void main(String[] args) { FileInputStream

Десериализация

class ObjectInputDemo {
public static void main(String[] args) {
FileInputStream fis

= null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("I:\\FileIO\\employee.dat");
ois = new ObjectInputStream(fis);
Employee emp = (Employee) ois.readObject();
System.out.println(emp);
System.out.println("Total number of employees: " + Employee.getNumEmployees());
} catch (IOException e) {
System.out.println("An I/O error occured");
} catch (ClassNotFoundException e) {
System.out.println("Class was not found");
}
finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
Employee [name=Robert, yearOfBirth=1987, gender=M, isMarried=true, salary=30000]
Total number of employees: 0

Total number of employees: 0

Слайд 13

Десериализация

Десериализация

Слайд 14

Сериализация графа объектов


Сериализация графа объектов

Слайд 15

Сериализуемый класс со ссылкой public class Person implements Serializable{ public Person(String

Сериализуемый класс со ссылкой

public class Person implements Serializable{
public Person(String name)

{
this.name = name;
System.out.println("Person constructor is called, name=" + name);
}
public Person() {
this.name = "A person";
System.out.println("Person parameterless constructor is called, name="
+ name);
}
public String getName() {
return name;
}
public void setSpouse(Person value) {
spouse = value;
}
public Person getSpouse() {
return spouse;
}
public String toString() {
return "[Person: name=" + name + " spouse=" + spouse.getName() + "]";
}
private String name;
private Person spouse;
}
Слайд 16

Сериализация public class TwoObjectsOutputDemo { public static void main(String[] args) {

Сериализация

public class TwoObjectsOutputDemo {
public static void main(String[] args) {
Person

ann = new Person("Ann");
Person bob = new Person("Bob");
ann.setSpouse(bob);
bob.setSpouse(ann);
System.out.println(ann);
System.out.println(bob);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("I:\\FileIO\\person.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(ann);
} catch (IOException e) {
System.out.println("An I/O error occured");
} finally {
try {
if (oos != null)
oos.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
Слайд 17

Сериализация Person constructor is called, name=Ann Person constructor is called, name=Bob

Сериализация
Person constructor is called, name=Ann
Person constructor is called, name=Bob
[Person: name=Ann spouse=Bob]
[Person:

name=Bob spouse=Ann]
Слайд 18

Десериализация class TwoObjectsInputDemo { public static void main(String[] args) { FileInputStream

Десериализация

class TwoObjectsInputDemo {
public static void main(String[] args) {
FileInputStream fis

= null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("I:\\FileIO\\person.dat");
ois = new ObjectInputStream(fis);
Person ann = (Person) ois.readObject();
System.out.println(ann);
System.out.println(ann.getSpouse());
} catch (IOException e) {
System.out.println("An I/O error occured");
} catch (ClassNotFoundException e) {
System.out.println("Class was not found");
}
finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
[Person: name=Ann spouse=Bob]
[Person: name=Bob spouse=Ann]
Слайд 19

Несериализуемые поля


Несериализуемые поля

Слайд 20

Несериализуемые поля

Несериализуемые поля

Слайд 21

Класс с несериализуемым полем class Salesman implements Serializable { public Salesman(String

Класс с несериализуемым полем

class Salesman implements Serializable {
public Salesman(String n,

double s) {
name = n;
salary = s;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public String toString() {
return getClass().getSimpleName() + "[name=" + name + ",salary=" + salary
+ ",bonus=" + bonus + "]";
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
private String name;
private double salary;
private transient double bonus;
}
Слайд 22

Сериализация public class TransientOutputDemo { public static void main(String[] args) {

Сериализация

public class TransientOutputDemo {
public static void main(String[] args) {
Salesman bob

= new Salesman("Robert", 30000);
bob.setBonus(10000);
System.out.println(bob);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("I:\\FileIO\\salesman.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(bob);
} catch (IOException e) {
System.out.println("An I/O error occured");
} finally {
try {
if (oos != null)
oos.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
Salesman[name=Robert,salary=30000.0,bonus=10000.0 ]

bonus=10000.0

Слайд 23

Десериализация class TransientInputDemo { public static void main(String[] args) { FileInputStream

Десериализация

class TransientInputDemo {
public static void main(String[] args) {
FileInputStream fis

= null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("I:\\FileIO\\salesman.dat");
ois = new ObjectInputStream(fis);
Salesman bob = (Salesman) ois.readObject();
System.out.println(bob);
} catch (IOException e) {
System.out.println("An I/O error occured");
} catch (ClassNotFoundException e) {
System.out.println("Class was not found");
}
finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
Salesman[name=Robert,salary=30000.0,bonus=0.0 ]

bonus=0.0

Слайд 24

UID


UID

Слайд 25

UID

UID

Слайд 26

I:\item>dir Volume in drive I has no label. Volume Serial Number

I:\item>dir
Volume in drive I has no label.
Volume Serial Number

is 44AB-CB89
Directory of I:\item
02/21/2013 12:14 PM .
02/21/2013 12:14 PM ..
02/21/2013 12:11 PM 476 ItemUID.java
1 File(s) 476 bytes
2 Dir(s) 48,619,651,072 bytes free
I:\item>javac ItemUID.java
I:\item>dir
Volume in drive I has no label.
Volume Serial Number is 44AB-CB89
Directory of I:\item
02/21/2013 12:16 PM .
02/21/2013 12:16 PM ..
02/21/2013 12:16 PM 752 ItemUID.class
02/21/2013 12:11 PM 476 ItemUID.java
2 File(s) 1,228 bytes
2 Dir(s) 48,619,646,976 bytes free
I:\item>serialver ItemUID
ItemUID: static final long serialVersionUID = -3358310746251373045L;
I:\item>

Получение UID

Слайд 27

serialVersionUID

serialVersionUID

Слайд 28

Класс с serialVersionUID public class ItemUID implements Serializable{ private static final

Класс с serialVersionUID

public class ItemUID implements Serializable{
private static final long serialVersionUID

= 5210454654602398740L;
public ItemUID(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public String toString() {
return "[name=" + name + ", number=" + number + "]";
}
private String name;
private int number;
}
Слайд 29

Сериализация public class UIDObjectOutputDemo { public static void main(String[] args) {

Сериализация

public class UIDObjectOutputDemo {
public static void main(String[] args) {
ItemUID

coffemaker = new ItemUID("Coffemaker", 2912);
System.out.println(coffemaker);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("I:\\FileIO\\item.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(coffemaker);
} catch (IOException e) {
System.out.println("An I/O error occured");
} finally {
try {
if (oos != null)
oos.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
[name=Coffemaker, number=2912]
Слайд 30

Новый класс со старым serialVersionUID public class ItemUID implements Serializable{ private

Новый класс со старым serialVersionUID

public class ItemUID implements Serializable{
private static final

long serialVersionUID = 5210454654602398740L;
public ItemUID(String name, int number, String description) {
this.name = name;
this.number = number;
this.description = description;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public String toString() {
return "[name=" + name + ", number=" + number + ", description=" + description+"]";
}
private String name;
private int number;
private String description;
}
Слайд 31

Десериализация class UIDObjectInputDemo { public static void main(String[] args) { FileInputStream

Десериализация

class UIDObjectInputDemo {
public static void main(String[] args) {
FileInputStream fis

= null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("I:\\FileIO\\item.dat");
ois = new ObjectInputStream(fis);
ItemUID item = (ItemUID) ois.readObject();
System.out.println(item);
} catch (IOException e) {
System.out.println("An I/O error occured");
} catch (ClassNotFoundException e) {
System.out.println("Class was not found");
}
finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
[name=Coffemaker, number=2912, description=null]
Слайд 32

readObject и writeObject


readObject и writeObject

Слайд 33

readObject и writeObject

readObject и writeObject

Слайд 34

Класс реализующий список с помощью массива public class StringArrayList implements Serializable

Класс реализующий список с помощью массива

public class StringArrayList implements Serializable {

private transient int size = 0;
private transient String buf[] = new String[16];
public void add(String s) {
buf[size] = s;
size++;
}
public String toString() {
StringBuffer b = new StringBuffer();
for (int i=0; i b.append(buf[i]);
b.append(" ");
}
return b.toString();
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(size);
for (int i=0; i s.writeObject(buf[i]);
}
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
int size = s.readInt();
for (int i = 0; i < size; i++)
add((String)s.readObject());
}
}
Слайд 35

Сериализация public class CustomOutputDemo { public static void main(String[] args) {

Сериализация

public class CustomOutputDemo {
public static void main(String[] args) {
StringLinkedList sList

= new StringLinkedList();
sList.add("apple");
sList.add("orange");
sList.add("banana");
System.out.println("List contents are: " + sList);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("I:\\FileIO\\fruitlist.dat");
oos = new ObjectOutputStream(fos);
System.out.println("Serializing .....");
oos.writeObject(sList);
} catch (IOException e) {
System.out.println("An I/O error occured");
} finally {
try {
if (oos != null)
oos.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
List contents are: banana orange apple
Serializing .....
Слайд 36

Десериализация class CustomInputDemo { public static void main(String[] args) { FileInputStream

Десериализация

class CustomInputDemo {
public static void main(String[] args) {
FileInputStream fis

= null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("I:\\FileIO\\fruitlist.dat");
ois = new ObjectInputStream(fis);
System.out.println("Deserializing .....");
StringLinkedList sList = (StringLinkedList) ois.readObject();
System.out.println("List contents are: " + sList);
} catch (IOException e) {
System.out.println("An I/O error occured");
} catch (ClassNotFoundException e) {
System.out.println("Class was not found");
}
finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}
}
Deserializing .....
List contents are: apple orange banana