package Demo02.ObjectStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
* 将一个对象存储到持久化(硬盘)的设备上。
*/
public class ObjectStreamDemo01 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
writeObj();// 对象的序列化。
readObj();// 对象的反序列化。
}
private static void readObj() throws IOException, ClassNotFoundException {
// 1,明确读取对象的文件
FileInputStream in = new FileInputStream("D:\\1.txt");
// 2,给操作文件对象加入写入对象功能。
ObjectInputStream ois = new ObjectInputStream(in);
Object object = ois.readObject();
Person person = (Person) (object);
// Person person = (Person)ois.readObject();
System.out.println(person);
}
private static void writeObj() throws IOException {
// 1,明确存储对象的文件。
FileOutputStream out = new FileOutputStream("D:\\1.txt");
// 2,给操作文件对象加入写入对象功能。
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(new Person("wangcai", 12));
// 3,调用了写入对象的方法。
oos.close();
// 关闭资源。
System.out.println("------");
}
}
package Demo02.ObjectStream;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private static String name;// 静态关键字static
private transient int age;// 瞬态关键字transient不用被序列化
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
}
|
|