对象流 这个叫着感觉有点别扭 主要就是表达这个意思。之前我们传输的都是基础数据为主,所以补充一个比较特别的
就是把java里的对象作为数据流输出/写入。
注意:对象需要实现序列化接口。 对象内的属性如果是引用了其他对象 那么其他对象一样需要序列化。
如果我们不希望将某些对象属性转换为流,则必须为此使用transient关键字。(spring更方便会有transient注解)
开发过web开发的朋友应该会熟悉 让你把对象转为json格式发送到前端的时候 就需要序列化。这也就侧面说明了数据发往了前端的过程中 发生了序列化。
创建一个对象 写入文件 再输出。
public class TestStream {
public static void main(String[] args) {
//创建一个Hero garen
//要把Hero对象直接保存在文件上,务必让Hero类实现Serializable接口
Hero h = new Hero();
h.name = "garen";
h.hp = 616;
//准备一个文件用于保存该对象
File f =new File("d:/garen.lol");
try(
//创建对象输出流
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos =new ObjectOutputStream(fos);
//创建对象输入流
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois =new ObjectInputStream(fis);
) {
oos.writeObject(h);
Hero h2 = (Hero) ois.readObject();
System.out.println(h2.name);
System.out.println(h2.hp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这时候你会想 单个对象一个一个读写岂不累死?
我发现list集合也是可以读写的! 如下:
public class ObjectOutAndInStream {
public static void main(String[] args) {
File file = new File("e:/SCfile/serral.txt");
IndexData indexData1 =new IndexData();
indexData1.setClosePoint(1231);
indexData1.setDate("2015");
IndexData indexData2 =new IndexData();
indexData2.setClosePoint(1231);
indexData2.setDate("2015");
List<IndexData>list = new LinkedList<>();
list.add(indexData1);
list.add(indexData2);
try (FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream =new ObjectOutputStream(fileOutputStream);
FileInputStream fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream =new ObjectInputStream(fileInputStream)
){
objectOutputStream.writeObject(list);
List<IndexData>indexDataList = (List<IndexData>)objectInputStream.readObject();
System.out.println(indexDataList.get(1).getClosePoint()+indexDataList.get(1).getDate());
}catch (Exception e){
e.printStackTrace();
}
}
}
依次类推 那么set map 这类也应该是可以的
我猜的。 有空可以再验证一下