30 IO流再回顾,深入理解序列化和反序列化


📖博主介绍


个人主页: Zinksl
编程社区: Zinksl编程酒馆
个人格言: 想法落实的最佳时机就是现在!🏄

如果你 喜欢交流热爱分享欢迎加入编程社区交流群 大家一起学习技术,交流心得,共同进步🚅


在这里插入图片描述


1 InputStream

在这里插入图片描述

代码示例:

public class FileInputStreamDemo {
    public static void main(String[] args) throws Exception {
//        定义文件路径
        String str = "E:\\Codes\\myProject\\fileInputStreamTest.txt";
//        创建FileInputStream对象
        FileInputStream fileInputStream = new FileInputStream(str);
//        创建一个8个字节的缓冲空间
        byte buffer [] = new byte[8];
        int length = 0;
        while ((length = fileInputStream.read(buffer)) != -1){
            System.out.println(new String(buffer,0,length));
        }

    }
}

2 OutputStream

代码示例:

此种方式数据写入文件,是覆盖源文件;

public class FileOutputSteamDemo {
    public static void main(String[] args) throws IOException {
        String str = "E:\\Codes\\myProject\\fileInputStreamTest.txt";
        OutputStream outputStream = new FileOutputStream(str);
        byte [] buffer = "gym.IverryverryLoveyou".getBytes();
        try {
            outputStream.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            outputStream.close();
        }
        System.out.println("完成写入");
    }
}

如果想实现数据写入文件,追加而不是覆盖则可以采用以下构造器:

  • public FileOutputStream( filesrc, boolean append)

参数append为true时则,追加数据,不覆盖,

3 文件拷贝(字节流)

拷贝代码示例

public class IOCopyDemo {
    public static void main(String[] args) throws IOException {
        String str = "E:\\Codes\\myProject\\copyTest.txt";
        String str2 = "E:\\Codes\\myProject\\coptTest2.txt";
//        创建输入流对象
        FileInputStream fileInputStreamDemo = new FileInputStream(str);
//        创建输出流对象
        FileOutputStream fileOutputStream = new FileOutputStream(str2);
//        创建缓冲
        byte buffer [] = new byte[8];
        int leng = 0;
//        用循环实现拷贝
        try {
            while ((leng = fileInputStreamDemo.read(buffer))!=-1){
                fileOutputStream.write(buffer,0,leng);

            }
        } finally {
            if (fileOutputStream != null || fileInputStreamDemo != null){
                fileInputStreamDemo.close();
                fileOutputStream.close();
            }
        }
        System.out.println("拷贝完成");
    }
}

4 FileReader、 FileWriter

在这里插入图片描述

FileWriter同样有两种模式,覆盖模式,和追加模式;
覆盖模式;使用以下构造器

  • public FileWriter( fileName)

使用下面构造器append 设置为true是是追加模式;

  • public FileWriter( fileName, boolean append)

注意事项:FileWriter使用之后必须关闭(close)或者刷新(flush),否则写不到文件中;

5 文件拷贝(字符流)

public class CopyDemo2 {
    public static void main(String[] args) throws FileNotFoundException {
        String  str = "E:\\Codes\\myProject\\fileWriter.txt";
        String str2 = "E:\\Codes\\myProject\\fileCopy.txt";
//        创建字符输入流
        FileReader fileReader = new FileReader(str);
        char [] array = new char[10];
        int leng=0;
//        创建字符输出流

        try {
            FileWriter fileWriter = new FileWriter(str2);
            while ((leng = fileReader.read(array)) !=-1){
                String s =new String(array,0,leng);
                fileWriter.write(s);
//                刷新字符输出流
                fileWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
    }
}

6 节点流和处理流

节点流是针对某个特定的数据源读写,如FileWriter、FileReader;处理流也叫包装流,连接已存在的流,为程序提供更强大的功能如BufferWriter、BufferReader;

7 ObjectOutputSteam和ObjectInputStream—序列化和反序列化

此处理流(包装流),提供了对基本类型或者对象类型的序列化和反序列化的方法;
ObjectOutputStream:提供了序列化的方法
ObjectInputStream:提供了反序列化的方法

序列化: 就是将数据与数据类型都保存起来,叫序列化;
反序列化:指将序列化的数据恢复到原来;

注意:如果想让某个对象支持序列化,则必须让其类是可序列化的,也就是必须让类实现两个接口:
Sarializable:标记接口,没有方法(推荐使用)
Externalizable:该接口有方法需要实现
序列化代码示例:

public class SerializableDemo {
    public static void main(String[] args) throws IOException {
//        创建被序列化对象
        Person xiaoM = new Person("小明",18);
//        创建文件路径
        String str = "E:\\Codes\\myProject\\ObjectOut.dat";
//        创建处理流对象
        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(str));
        outputStream.writeObject(xiaoM);
        outputStream.close();
        System.out.println("序列化完成");
    }
}
class Person implements Serializable {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Person{name = " + name + ", age = " + age + "}";
    }
}

反序列化代码示例:

public class ReSerializableDmeo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
//        定义变量接收,反序列化数据
        Person person = null;
        //        创建文件路径
        String str = "E:\\Codes\\myProject\\ObjectOut.dat";
//        创建ObjectInputStream对象
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(str));
        person = (Person) objectInputStream.readObject();
        objectInputStream.close();
        System.out.println("反序列化完成!");
        System.out.println("姓名:"+person.getName()+"  年龄:"+person.getAge());
    }
}

序列化过程中需要注意的事项:
(1):读写顺序要一致
(2):要实现序列化的的对象,类必须实现Serializable接口
(3):序列化类中建议添加 SerialVersionUID,可以提高版本兼容性
(4):序列化时会默认将里面所有属性都序列化了,但是被static和transient修饰的属性不会被序列化;
(5):序列化时要求里面属性的类型也需要实现序列化接口
(6):序列化具有可继承性

8 转换流

InputStreamReader和OutputStreamWriter
代码示例:

public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
        String str = "E:\\Codes\\myProject\\fileWriter.txt";
        InputStreamReader inputStreamReader = new InputStreamReader(new  FileInputStream(str),"gbk");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String s = null;
        while ((s = bufferedReader.readLine()) != null){
            System.out.println(s);
            bufferedReader.lines();
        }
        inputStreamReader.close();
        bufferedReader.close();
    }
}

结尾彩蛋

认真分享技术,记录学习点滴若内容对你有用可以鼓励一下🍻方式如下
点赞:👍 留言:✍收藏:⭐️

如有疑问欢迎评论区留言,或加入技术交流群:1002743802
关注我订阅专栏,会持续体系化更新哦👈

  • 23
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 30
    评论
评论 30
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zinksl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值