必须实现序列化接口
- package ObjectOutputstreamTeast;
-
- import java.io.FileOutputStream;
- import java.io.ObjectOutput;
- import java.io.ObjectOutputStream;
-
- public class ObjectOS {
- // 目标:掌握对象字节输出流的使用 序列化对象
- public static void main(String[] args) {
-
- try ( //创建字节对象
- ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("src/zfile1/mamat002.txt"));
- ){
- //创建对象
- OBuser u=new OBuser("admin","mamat",26,"6666888zx");
- oos.writeObject(u);
- System.out.println("序列化成功");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- }
-
- package ObjectOutputstreamTeast;
-
- import java.io.Serializable;
-
- public class OBuser implements Serializable {
-
-
- private String loginName;
- private String userName;
- private int age;
- private transient String password;
- //加上 transient 这个成员不参加序列化
- public OBuser() {
- }
-
- public OBuser(String loginName, String userName, int age, String password) {
- this.loginName = loginName;
- this.userName = userName;
- this.age = age;
- this.password = password;
- }
-
- public String getLoginName() {
- return loginName;
- }
-
- public void setLoginName(String loginName) {
- this.loginName = loginName;
- }
-
- public String getUserName() {
- return userName;
- }
-
- public void setUserName(String userName) {
- this.userName = userName;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- @Override
- public String toString() {
- return "OBuser{" +
- "loginName='" + loginName + '\'' +
- ", userName='" + userName + '\'' +
- ", age=" + age +
- ", password='" + password + '\'' +
- '}';
- }
- }
- package ObjectOutputstreamTeast;
-
- import java.io.FileInputStream;
- import java.io.ObjectInputStream;
-
- public class Test {
- public static void main(String[] args) {
- //创建一个对象字符输入管道,包装 低级的输入流与源文件接通
- try ( ObjectInputStream ois= new ObjectInputStream(new FileInputStream("src/zfile1/mamat002.txt"));
- ){
- System.out.println((OBuser)(ois.readObject()));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }