对象流Object ,对象要先序列化才能写入;

15 篇文章 0 订阅
import java.io.Serializable;
//先写出一个Student类方便new对象 ,重写toString方法方便输出;
public class Student implements Serializable{
//这里要实现Serializable接口,这是标记接口,类似 colenable接口;告诉程序该对象可被序列化;

private static final long serialVersionUID = 1L;
//ID用途可以在修改对象的属性的时候另一边输出不会报错,增加或者修改的参数会默认为初始值;

private String name;
private int num;

public Student(String name, int num) {
super();
this.name = name;
this.num = num;
}
@Override
public String toString() {
return "Student [name=" + name + ", num=" + num + "]";
}

}

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TestObject {
static String []s = {"自动","都是","大方","感受到"};
static String s1 = "sfsfsgfsgsgs";
static Student s2 = new Student("李上",22);
static Student s3 = new Student("发的",22);
static Student s4 = new Student("风扇",22);
static Student s5 = new Student("df",22);
//new出对象,也可以直接把对象挨个写入文件中,再挨个读出来;
//当用while读取多个对象时候要用到while(Objiet!=null) {}
//程序会在读取到最后一个的时候继续读取下一个,然后报错,预防的方法是
//在写入时候最后写入一个null对象,当读取到null时候程序就会跳出循环;

public static void main(String[] args) {
TestObject t =new TestObject();

t.testw();
t.testr();

}
public void testw() {
File f = new File("G:\\demo\\x.txt");
List<Student> ls = new ArrayList<>();
ls.add(s2);
ls.add(s3);
ls.add(s4);
ls.add(s5);
//把对象放入集合中

ObjectOutputStream oos =null;
try {
oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(ls);
//把整个集合写入文件之中;
System.out.println();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



public void testr() {
File f = new File("G:\\demo\\x.txt");

ObjectInputStream ois =null;
try {
ois = new ObjectInputStream(new FileInputStream(f));
List<Student> ls=  (List<Student>) ois.readObject();
//读取时候要注意输出对象的类型,放入什么类型就要用什么类型来接收;
System.out.println(ls);
//打印时候也要注意对象类型的转化;

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}


//最后要注意在使用完流之后要使用close();方法关闭;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值