ObjectStream
package File類;
import java.io.*;
public class ObjectStreamDemo {
public static void main(String[] args) {
// write();
read();
}
// obj要寫入文件日杈,所以要序列化
public static void write() {
try {
Dog dog = new Dog("哈哈", 2);
File file = new File("obj.txt");
OutputStream outputStream = new FileOutputStream(file);
ObjectOutputStream write = new ObjectOutputStream(outputStream);
write.writeObject(dog);
write.close();
} catch (Exception e) {
}
}
// 讀取obj文件琅摩,所以要反序列化
public static void read() {
try {
File file = new File("obj.txt");
InputStream in = new FileInputStream(file);
ObjectInputStream read = new ObjectInputStream(in);
Dog dog =(Dog)read.readObject();
System.out.println(dog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Dog類
package File類;
import java.io.Serializable;
// 對象序列化 Serializable 類
// 1抄谐、對象數(shù)據(jù)用于保存文件就要序列化
// 2、對象數(shù)據(jù)用于網(wǎng)絡傳輸也要序列化
public class Dog implements Serializable {
private String name;
private int age;
public Dog() {
}
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
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 String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者