File.io读取文件(六)

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class ObjectSerializeDemo {
public static void main(String[] args) {
String path="D:/aa.txt";
serialeTo(path);
seriale(path);
}


//反序列化
public static void seriale(String srcpath){
try(
ObjectInputStream bis=new ObjectInputStream(
new BufferedInputStream(
       new FileInputStream(
        new File(srcpath))));
){
   Object obj=bis.readObject();
   Student st=null;
   if(obj instanceof Student){
    st=(Student)obj;
   }
//bis.close();
   System.out.println(st.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//序列化
public static void serialeTo(String destpath){
//创建数据源
Student st=new Student("杨幂",33);

File fos=new File(destpath);//无论保存什么格式类型的文件,都是乱码,这里
try(//jdk1.7,资源关闭新特性
ObjectOutputStream dos=new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(fos)));
){
dos.writeObject(st); 

dos.flush();//刷新管道数据
//dos.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


//要实现对象反序列化/序列化必须实现Serializable接口
class Student implements java.io.Serializable{
private String name;
private  transient int age;//不需要序列化,就用transient修饰
public Student() {
}
public Student(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 "Student [name=" + name + ", age=" + age + "]";
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值