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



    在这里插入图片描述
    📖 个人介绍


    大家好我是:一颗松
    认真分享技术,记录学习点滴
    如果分享对你有用请支持我哦🍺

    点赞:👍 留言:✍收藏:⭐️
    个人格言: 想法落实的最佳时机就是现在!🏄


    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));
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    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("完成写入");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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

    • 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("拷贝完成");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    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 {
    
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    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 + "}";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    反序列化代码示例:

    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
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    序列化过程中需要注意的事项:
    (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();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    结语

    大佬请留步在这里插入图片描述既然看到这了不如点个赞👍再走吧

    本文目的在于分享技术以及在学习过程中个人记得需要注意的点,记录学习过程;
    如果出现错误欢迎大家指正,如有意见或建议欢迎在评论区讨论

  • 相关阅读:
    QT在安装后添加新组件【QT基础入门 环境搭建】
    LeetCode 290. 单词规律
    涨工资不是程序员跳槽的理由
    使用 conda 在 Ubuntu 16.04 上安装 Python 3.9 的步骤:和 VSCode配置
    BUUCTF 隐藏的钥匙 1
    记录一次关于Rank()排序函数问题
    最优二叉搜索树问题(Java)
    Elasticsearch:运用向量搜索通过图像搜索找到你的小狗
    Use the OverlayFS storage driver
    linux服务器监控性能测试
  • 原文地址:https://blog.csdn.net/Zinkse/article/details/126029047