Wednesday, July 11, 2012

I/O - Getting better understanding of API


Let's start with the class File

package br.com.ocjp.io;
import java.io.File;
import java.io.IOException;
public class ClassFile {
public static void main(String[] args) {
File f = new File("C:\\temp\\file.txt"); // There is no file yet.
System.out.println("Does the file exist? " + f.exists());
try {
boolean flag = f.createNewFile(); // May Create a real file
System.out.println("File has been created " + flag);
System.out.println("Does the file exist? " + f.exists());
} catch (IOException e) {}
}
}
view raw gistfile1.java hosted with ❤ by GitHub

Notice that the file has not been created until the line 13 be reached, to memorize it think of when you create a File(line 10) it doesn't throw any exception but the method createNewFile does.

Serialization

Serialization is the mechanism that allows you save the state of objects.
Find below the keys to make a class serializable.

package br.com.ocjp.serializable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
class Request implements Serializable {
public int number;
public Date create;
public String description;
}
public class Serialization {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Request request = new Request();
request.number = 100;
request.create = new Date();
request.description = "@@ version 1.3 @@";
FileOutputStream output = new FileOutputStream("C:\\temp\\request.ser");
ObjectOutputStream os = new ObjectOutputStream(output);
os.writeObject(request);
os.close();
FileInputStream file = new FileInputStream("C:\\Temp\\request.ser");
ObjectInputStream io = new ObjectInputStream(file);
Request r = (Request) io.readObject();
System.out.println(r.number);
System.out.println(r.create);
System.out.println(r.description);
}
}
view raw gistfile1.java hosted with ❤ by GitHub

First of all we have to implement the interface serializable( look at line 11), also to save the state of object we need the classes FileOutputStream and ObjectOutputStream, the writeObject(object) method is responsible for it and to retrieve the serializable object from the file we need FileInputStream and ObjectInputStream the readObject() is responsible for reading it.

!Import

- If you don't want to save a member of object you must mark it as transient
- Whether a super class implements Serializable its subclasses are indirectly Serializable
- Whether a subclass implements Serializable and a superclass doesn't the constructor will be invoked as well as the instance variable will get their default values

Let's see an example:
package br.com.ocjp.serializable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Something {
Something() {
System.out.println("Something constructor");
}
}
class Animal extends Something {
Animal() {
System.out.println("Animal constructor");
}
String name = "something";
int age;
}
class Dog extends Animal implements Serializable {
Dog() {
System.out.println("Dog constructor");
}
String kind;
String owner;
}
public class SerializableExamples {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileOutputStream out = new FileOutputStream("C:\\temp\\animal.ser");
ObjectOutputStream st = new ObjectOutputStream(out);
Dog a1 = new Dog();
a1.age = 5;
a1.name = "Dog";
a1.kind = "Pet";
a1.owner = "Somebody";
st.writeObject(a1);
}
}
view raw gistfile1.java hosted with ❤ by GitHub

Let's see what's been saved.
package br.com.ocjp.serializable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Input {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream f = new FileInputStream("C:\\temp\\animal.ser");
ObjectInputStream in = new ObjectInputStream(f);
Dog a2 = (Dog)in.readObject();
System.out.println("Age ==> " + a2.age);
System.out.println("Name ==> " + a2.name);
System.out.println("Kind ==> " + a2.kind);
System.out.println("Owner ==> " + a2.owner);
}
}
view raw gistfile1.java hosted with ❤ by GitHub



- if you wanna save a state of object that has a reference to another object which does not implement Serializable you have to write the methods writeObject() and readObject().

package br.com.ocjp.serializable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Monitor {
String model;
}
class PC implements Serializable {
String system;
int version;
public transient Monitor monitor;
private void writeObject(ObjectOutputStream o) {
try {
o.defaultWriteObject();
o.writeObject(monitor.model);
} catch (IOException e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream in) {
try {
in.defaultReadObject();
Monitor m = new Monitor();
m.model = (String)in.readObject();
this.monitor = m;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch( IOException e) {}
}
}
public class WriteReadObject {
public static void main(String[] args) {
PC m = new PC();
m.system = "iOS";
m.version = 1;
Monitor d = new Monitor();
d.model = "SX465";
m.monitor = d;
try {
FileOutputStream f = new FileOutputStream("C:\\temp\\pc.ser");
ObjectOutputStream out = new ObjectOutputStream(f);
out.writeObject(m);
FileInputStream f1 = new FileInputStream("C:\\temp\\pc.ser");
ObjectInputStream in = new ObjectInputStream(f1);
PC pc = (PC)in.readObject();
System.out.println("PC Monitor ==> " + pc.monitor.model);
} catch (IOException e) {
System.out.println("Cannot save it");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
view raw gistfile1.java hosted with ❤ by GitHub

- Finally we can use serialization with static variables but as you've seen serialization is useful for objects

Print this post

No comments: