Android解析字节流数据文件

接着上篇文章所请求生成的字节流数据文件,开始解析。

解析byte[]类型的文件,需要有其内部数据的数据格式,下面举个栗子:

说明:类型长度  Uint32  为(4BYTES)Uint8  为(1BYTES)

typedef struct _tag_DATA_INFO{

            Uint32 ID ; //ID--------->4个字节

            Uint8 name[32]; //名称-------->32个字节

            Uint32 competence;//权限

            Uint32 Sort;//排序

            Uint8  reserve[128];//保留字段

        }TFLOOR_INFO,*PFLOOR_INFO;

1.把这个数据格式的长度计算出来,以此为例,长度为:4+32+4+4+128=172

   即:这个字节流文件是以172个字节为一个单元,各个单元首位相连组合成的一个大的文件

2.把这个数据格式变成我们Android的bean类

public class Data{
    private int ID;
    private String name;
    private int competence;
    private int Sort;
    private String  reserve;

    public Floor(int ID, String name, int competence, int sort) {
        this.ID = ID;
        this.name = name;
        this.competence = competence;
        Sort = sort;
    }
    //此处自行添加get、set等方法
}

3.开始解析

==========以下是核心代码==========

private static List getData(File file) throws UnsupportedEncodingException {
    List<Data> list = new ArrayList<>();
    byte[] data = readFileToString(file); //先将文件以流的方式转换成字节数组
    int divLength = 172;
    int count = data.length / divLength; //以172长度为单位,获取需要循环的次数
    for (int i = 0; i < count; i++) { //循环逐个解析字节
        int ID = ByteUtil.getInt(data, 0 + (i * divLength)); //data为数据源,第二个参数为偏移量
        String name = new String(data, 4 + (i * divLength), 32, "UTF-8"); //偏移量要之前的偏移量逐个相加
        int competence = ByteUtil.getInt(data, 36 + (i * divLength)); //偏移量=4+32+(i * divLength)
        int Sort = ByteUtil.getInt(data, 40 + (i * divLength)); //偏移量=4+36+(i * divLength)
        Data data = new Data(ID, name, competence, Sort);
        list.add(data);
        //此处可以将list打印一下看看
    }
    return list;
}

==========以上是核心代码==========

==========以下是工具类方法==========

/**
 * 将文件读取为字节数组
 * @param file
 * @return
 */
public static byte[] readFileToString(File file) {
    FileInputStream input = null;
    byte[] buf = new byte[0];
    try {
        input = new FileInputStream(file);
        buf = new byte[input.available()];
        input.read(buf);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return buf;
}
public static int getInt(byte[] bytes,int index) { //这里只写了Int的解析方法,其他可自行搜索
    return (0xff & bytes[index]) | (0xff00 & (bytes[index+1] << 8)) | (0xff0000 & (bytes[index+2] << 16)) | (0xff000000 & (bytes[index+3] << 24));
}

==========以上是工具类方法==========

猜你喜欢

转载自blog.csdn.net/S_Alics/article/details/81561940