按约定规则解析16进制为中文或者英文

参考文章 Java 十六进制(Hex)与byte数组之间的转换

总体思路:
16进制   --->  转为byte字节 
 		 --->  取具体约定的字节个数组成字节数组  
 		 --->  调用 new String(nameBytes,"GB18030") 方法获得中文或者英文
import net.sf.json.JSONArray;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 解析16进制的报文数组数据
 **/
public class ParseHex {

    /**
     * 解析打印数组,返回解析后的数组
     * @param printData 16进制打印数据
     * @param filePath  读取文件的路径
     * @param 
     * @return 解析后的集合
     * @throws IOException
     */
    public static <T> List<T> parsePrintDataToList(String printData,String filePath) throws IOException {
        byte[] printBytes = hexToByteArray(printData);
        System.out.println(Arrays.toString(printBytes));
        byte index = printBytes[0];
        byte[] nameBytes = new byte[index];
        Map<String,Object> map = new HashMap<>(16);
        if (index >= 0) { System.arraycopy(printBytes, 1, nameBytes, 0, index); }
        String name = new String(nameBytes,"GB18030");
        System.out.println(name);
        List<String> fields = Files.lines(FileSystems.getDefault().getPath(filePath))
                .map(str -> str.substring(0,1).toLowerCase() + str.substring(1))
                .collect(Collectors.toList());
        System.out.println("List fields = " +fields);

        int current = 1+index;
        List<Map<String,Object>> list = new ArrayList<>() ;
        int fieldIndex =0;
        while (current<printBytes.length) {
            current = current + 3;
            int length = (int)printBytes[current];
            current = current+1;
            byte[] contentBytes = new byte[length];
            if (length >= 0) {
                System.arraycopy(printBytes, current, contentBytes, 0, length);
            }
            String content = new String(contentBytes,"GB18030");
            map.put(fields.get(fieldIndex),content);
            fieldIndex = fieldIndex +1;
            current = current + length;
        }
        list.add(map);
        /*list.forEach(System.out::println);
        JSONArray jsonArray = JSONArray.fromObject(list);
        System.out.println(jsonArray);
        String s = jsonArray.toString();*/
        return (List<T>) list;
    }

    private static byte[] hexToByteArray(String inHex) {
        int hexLen = inHex.length();
        byte[] result;
        if (hexLen % 2 == 1){
            hexLen++;
            result = new byte[(hexLen / 2)];
            inHex = "0" + inHex;
        }else {
            result = new byte[(hexLen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexLen ; i += 2 ){
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    private static byte hexToByte(String inHex) {
        return (byte)Integer.parseInt(inHex,16);
    }
}

你可能感兴趣的:(Java笔记心得,java)