table of Contents
Serialization (the ObjectOutputStream)
Serialization: class can be converted into binary data transmission ( implements Serializable class can be serialized )
ObjectOutputStream(序列化) implements OutputStream。
A simple example:
class Animal implements Serializable{
private String eat;
private String write;
public Animal() {
}
public Animal(String eat, String write) {
this.eat = eat;
this.write = write;
}
public String getEat() {
return eat;
}
public void setEat(String eat) {
this.eat = eat;
}
@Override
public String toString() {
return "eat:" + this.eat + "、write:" + this.write;
}
}
public class Demo01 {
private static final File ANIMAL_FILE = new File("D:" + File.separator + "Hello.ses");
public static void main(String[] args) throws Exception {
test();
System.out.println(detest());
}
public static void test() throws Exception {
Animal an = new Animal("饭","水");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(ANIMAL_FILE));
oos.writeObject(an);
oos.close();
}
}
Deserialize (the ObjectInputStream)
By ObjectOutputStream.readObject () can read ObjectOutputStream.writeObject () information output.
ObjectInputStream(序列化) implements InputStream
A simple example:
public class Demo01 {
private static final File ANIMAL_FILE = new File("D:" + File.separator + "Hello.ses");
public static void main(String[] args) throws Exception {
detest();
}
public static void detest() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(ANIMAL_FILE));
Animal an = (Animal) ois.readObject();
System.out.println(an);
ois.close();
}
result
eat:饭、write:水
The actual development of the sequence general use third-party management tools, could be turned into text transmission structured, can all languages can be used.
transient
transient: in the process of the automatic sequence of operations (typically are automatically saved), the need to save the attribute declaration.
A simple example:
class Animal implements Serializable{
private transient String eat;
private transient String write;
public Animal() {
}
public Animal(String eat, String write) {
this.eat = eat;
this.write = write;
}
public String getEat() {
return eat;
}
public void setEat(String eat) {
this.eat = eat;
}
@Override
public String toString() {
return "eat:" + this.eat + "、write:" + this.write;
}
}
public class Demo01 {
private static final File ANIMAL_FILE = new File("D:" + File.separator + "Hello.ses");
public static void main(String[] args) throws Exception {
///test();
detest();
}
public static void test() throws Exception {
Animal an = new Animal("饭","水");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(ANIMAL_FILE));
oos.writeObject(an);
oos.close();
}
public static void detest() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(ANIMAL_FILE));
Animal an = (Animal) ois.readObject();
System.out.println(an);
ois.close();
}
}
result
transient: the data is not saved
eat:null、write:null