BufferInput/OutputStream ObjectInput/OutputStream

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
public class Buffertest {
    public static void main(String[] args) throws Exception{
        FileOutputStream fos=new FileOutputStream("a.txt");
        BufferedOutputStream bos=new BufferedOutputStream(fos);
        //用缓冲区来包装文件写入流

        DataOutputStream dataOutputStream=new DataOutputStream(bos);
        dataOutputStream.writeInt(1000);
        dataOutputStream.writeDouble(123.456);
        dataOutputStream.writeUTF("sadasd红啊a");
        //bos.flush();// 刷新或者关闭都可以讲缓冲区的数据放到文件中
        bos.close();
        FileInputStream fis=new FileInputStream("a.txt");
        BufferedInputStream bis=new BufferedInputStream(fis);
        DataInputStream dataInputStream=new DataInputStream(bis);
        System.out.println(dataInputStream.readInt());//保持顺序,不然会乱
        System.out.println(dataInputStream.readDouble());
        System.out.println(dataInputStream.readUTF());
        bis.close();

        ObjectOutputStream objectOutputStream=new ObjectOutputStream(fos);
//        ArrayList<String> names=new ArrayList<>();
//        names.add("张三");
//        names.add("李四");
//        names.add("王五");
        ArrayList<Person> names=new ArrayList<>();
        names.add(new Person("张三","13231231","男"));
        names.add(new Person("李四","131231","女"));
        names.add(new Person("王五","13231","男"));

        for (Person p:names){
            System.out.println(p);
        }
        objectOutputStream.writeObject(names);
        /**
         * 对对象进行串行化:如果将一个不能串行化的对象传递给writeObject方法,
         那么它抛出一个NotSerializable Exception
         对象只能在它的类实现了Serializable接口的情况下被串行化。
         自己新建的类class1,新建的时候引入Serializable接口就行了
         public class class1 implements Serializable{}
         然后再根据提示在类里加一个private static final long serialVersionUID = 1L;就行了。
         之后就可以使用writeObject(class1的实例)之类的函数了。
         public interface Serializable {
         }
         */
        objectOutputStream.close();

        FileInputStream fileInputStream=new FileInputStream("a.txt");
        ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
        System.out.println(objectInputStream.readObject());
        objectInputStream.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值