【java/二进制文件读写】将一个字符串双重链表存入二进制文件 及从二进制文件读取这个双重链表的例程

【前作】

https://www.cnblogs.com/heyang78/p/15993166.html

【代码】

package com.hy.lab.binrw;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args){
        List<List<String>> rowList=new ArrayList<>();
        rowList.add(Arrays.asList("Andy","Bill","Cindy","Douglas","Eliot","Felix"));
        rowList.add(Arrays.asList("杨志","才丢花石纲","又丢生辰纲","天暗星"));
        rowList.add(Arrays.asList("唐三藏","孙悟空","猪八戒","沙和尚","西凉女王","玉面公主","老鼠精"));

        String file="c:\\temp\\0610.dat";
        saveListToBinFile(rowList,file);

        List<List<String>> readList=loadListFromBinFile(file);
        for(List<String> lines:readList){
            for(String str:lines){
                System.out.print(str+",");
            }
            System.out.println();
        }
    }

    /**
     * 存储
     * @param rowList
     * @param filename
     */
    private static void saveListToBinFile(List<List<String>> rowList,String filename){
        try(DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));){
            out.writeInt(rowList.size());

            for(List<String> cells:rowList){
                int cellCnt=cells.size();
                out.writeInt(cellCnt);

                for(String cell:cells){
                    out.writeUTF(cell);
                }
            }

            System.out.println("输出完毕");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    // 读取
    private static List<List<String>> loadListFromBinFile(String filename){
        List<List<String>> rowList=new ArrayList<>();

        try(DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));){
            int lineCnt=in.readInt();
            for(int i=0;i<lineCnt;i++) {
                int cellCnt = in.readInt();

                List<String> cells=new ArrayList<>();
                for(int j=0;j<cellCnt;j++){
                    String cell=in.readUTF();
                    cells.add(cell);
                }

                rowList.add(cells);
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        return rowList;
    }
}

【输出】

Andy,Bill,Cindy,Douglas,Eliot,Felix,
杨志,才丢花石纲,又丢生辰纲,天暗星,
唐三藏,孙悟空,猪八戒,沙和尚,西凉女王,玉面公主,老鼠精,

END

posted @ 2022-06-10 13:35  逆火狂飙  阅读(137)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东