java读写二进制流

写入

public static void main(String[] args) throws FileNotFoundException, IOException {
  ObjectOutputStream oos=null;
  try{
  //创建ObjectOutputStream输出流
  oos=new ObjectOutputStream(new FileOutputStream("d:\\test\\student.txt"));
  Student stu=new Student("小明",22,"男","123456");
  //对象序列化,写入输出流
  oos.writeObject(stu);
  
  }catch(IOException ex){
   ex.printStackTrace();
  }finally{
   if(oos!=null){
    oos.close();
   }
  }
 }

读出

public static void main(String[] args) throws IOException, ClassNotFoundException  {
  ObjectInputStream ois=null;
  try{
  //创建ObjectOutputStream输出流
  ois=new ObjectInputStream(new FileInputStream("d:\\test\\student.txt"));
  //反序列化,强转类型
  Student stu=(Student)ois.readObject();
  //输出生成后对象信息
  System.out.println("姓名为:"+stu.getName());
  System.out.println("年龄为:"+stu.getAge());
  System.out.println("性别为:"+stu.getGender());
  System.out.println("密码为:"+stu.getpassword());
  }catch(IOException ex){
   ex.printStackTrace();
  }finally{
   if(ois!=null){
    ois.close();
   }
  }
 }

实体类

public class Student implements java.io.Serializable  { 
 private String name;
 private int age;
 private String gender;

 //transient使password不能序列化,所以不能从输入流中读出,该属性在控制台输出是null

 private transient String password;
 public Student(String name, int age,String gender,String password){
  System.out.println("带参数的构造方法");
  this.name=name;
  this.age=age;
  this.gender=gender;
  this.password=password;
 }
 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;
 }
 public String getGender() {
  return gender;
 }
 public void setGender(String gender) {
  this.gender = gender;
 }
 public String getpassword() {
  return password;
 }
 public void setpassword(String password) {
  this.password = password;
 }
}

转载于:https://my.oschina.net/u/3468198/blog/894041

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值