您的位置:首页 > 编程语言 > Java开发

Java 序列化反序列化文件

2012-03-15 16:59 330 查看
import java.io.*;

@SuppressWarnings("serial")
class Person implements Serializable {

public Person(String name, String sex, int age, int height) {
this.name = name;
this.sex = sex;
this.age = age;
this.height = height;
}

public String toString() {
return "|" + this.name + "|" + this.sex + "|" + this.age + "|"
+ this.height + "|";
}

public String name;
public String sex;
public int age;
public int height;
}

public class SerialTest {
public static void main(String[] args) throws FileNotFoundException,
IOException, ClassNotFoundException {

Person p = new Person("Jim", "male", 28, 194);

// 开始序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
new File("myTest.txt")));
oos.writeObject(p);

// 反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
new File("myTest.txt")));
Person p1 = (Person) ois.readObject();

System.out.println(p1.toString());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java string class file import