工作项目经验归纳--使用java解析分布式集成协议

一天就解决了一个问题:

解析协议

协议为分布式集成协议(不懂)

拿到很多的字节串,然后将这些字节串进行解析,需要确定好字节流的起始位置以及在解析这些内容的时候,分离出来获取的数据类型,通过获取字节流的内容信息,拿到所需要的内容

第一步:

动态加载本地文件,现在读取的是resource底下的内容,使用代码

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);

第二步:

将流内容转成string

String str = convertStreamToString(inputStream);
public  static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

第三步

将string转成byte数组,需要部分字节进行切割

byte[] byteArray = hexToByte(str);
public static byte[] hexToByte(String hex) {
        int m = 0, n = 0;
        hex = hex.replace(" ", "");
        // 每两个字符描述一个字节
        int byteLen = hex.length() / 2;
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
            ret[i] = (byte) intVal;
        }
        return ret;
    }

第四步:

将byte数组转成buffer,利用ByteBuffer现成的方法wrap

buffer = ByteBuffer.wrap(byteArray);

第五步:

让buffer确定好低端在前,同时确定好位置

buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.position(0);

第六步:

定义一个空参构造返回这个buffer

public static ByteBuffer shortTypeConversionUtil(){
        return buffer;
    }

第七步:

读取1024字节的数据时, 固定好获取的位置(为什么要单独写,因为需要的字节太多了,需要for循环获取)

public static Byte[] dataAnalysis() {
        Byte[] bytes = new Byte[1024];
        for (int i = 313; i < 1337; i++) {
            bytes[i] = buffer.get(i);
        }
        return bytes;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值