美文网首页
如何将一个Java对象序列化到文件里

如何将一个Java对象序列化到文件里

作者: 灰白界限 | 来源:发表于2017-11-09 15:29 被阅读0次
    
    
    import junit.framework.TestCase;
    
    import java.io.*;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Created by y_str on 2017/11/9 0009.
     */
    public class ObjectToFile extends TestCase {
        public void test(){
            List<Object> list = new ArrayList<Object>();
            UserObj user = new UserObj();
            user.setAge(20);
            user.setUserId(1000L);
            user.setUserName("测试");
            list.add(user);
            list.add(user);
            try {
                ObjectOutputStream ous = new ObjectOutputStream(new FileOutputStream("test.txt"));
                ous.writeObject(user);
                ous.writeObject(list);
                ous.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                ObjectInputStream ins =  new ObjectInputStream(new FileInputStream("test.txt"));
                UserObj obj = (UserObj)ins.readObject();
                List  tempList = (List)ins.readObject();
                System.out.println(obj.toString());
                System.out.println(tempList.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    class UserObj implements Serializable{
    
        private Long userId;
        private String userName;
        private Integer age;
    
    
        public Long getUserId() {
            return userId;
        }
    
        public void setUserId(Long userId) {
            this.userId = userId;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "UserObj{" +
                    "userId=" + userId +
                    ", userName='" + userName + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

    相关文章

      网友评论

          本文标题:如何将一个Java对象序列化到文件里

          本文链接:https://www.haomeiwen.com/subject/cptmmxtx.html