使用map集合对文件进行序列化和反序列化

实现效果图如下:

 代码如下:

    static String areFile1 = "D:\\xxx\\三国演义-副本.txt";

    public static void m1() throws IOException {
        TreeMap<String, String> mp = new TreeMap<>();
        String areFile = "D:\\xxx\\三国演义.txt";
        FileOutputStream fos = new FileOutputStream(areFile1);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        FileReader fileReader = new FileReader(areFile);
        BufferedReader br = new BufferedReader(fileReader);
        String lone = "";
        while ((lone = br.readLine()) != null) {
            String[] s = lone.split(" ");
            mp.put(s[0], s[1]);
        }
        System.out.println(mp);
        oos.writeObject(mp);
        System.out.println("序列化成功");
        oos.close();
        fileReader.close();
        br.close();
        fos.close();
    }

    public static void m2() throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream(areFile1);
        ObjectInputStream ois = new ObjectInputStream(fis);
        TreeMap<String, String> map = (TreeMap<String, String>) ois.readObject();
        System.out.println("反序列化成功");
        for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
            System.out.println(stringStringEntry.getKey() + stringStringEntry.getValue());
        }
        ois.close();
        fis.close();

    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        m1();
        m2();
    }


版权声明:本文为qq_57322340原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。