其他流的使用

  

输入输出流

数据流:

/*
    数据流
    DataInputStream和DataOutputStream
    作用:用于基本数据类型遍历或字符串的读取和写入
     */
    @Test
    public void test1() throws IOException {
//        写入操作
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        dos.writeUTF("张麻子");
        dos.flush();
        dos.writeInt(40);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();

        dos.close();
//        得到的data.txt文件无法直接读取
    }
    @Test
    //      将文件中的变量读入到到内存中
    public void test2() throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));

//      读取顺序要与写入文件时的顺序一致
        String name = dis.readUTF();
        int age = dis.readInt();
        boolean b = dis.readBoolean();
        System.out.println(name+age+b);

        dis.close();
    }

对象流:

 序列化:写入文件中

反序列化:从文件在写入内存中

 

  

package ObjectInputOutputStream;

import org.junit.Test;

import java.io.*;

public class ObjectStreamTest {

    /*
       将内存中的java对象保存到磁盘中或通过网络传输出去
       使用ObjectOutputStream实现
        */
    @Test
    public void test() throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ObjectStream.txt"));

        oos.writeObject(new String("我爱中国!"));
        oos.flush();

        oos.close();
    }

    /*
        反序列化:将磁盘文件(网络)中的对象还原为内存中的对象
        使用ObjectInputStream
     */
    @Test
    public void test2() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("ObjectStream.txt"));

        Object obj = ois.readObject();
        System.out.println(obj);

        ois.close();
    }
}

类的序列化有一定的要求:必须实现以下两个接口之一

 

static,transient的变量无法序列化 

 

若没有手动加serialVersionUID ,在修改对象后,JVM的UID会相应的改变导致无法反序列化 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值