Java读取文件到字节数组,16进制与字节数组的转化,每16个字节换行打印,字符串每隔两位插入空格

Java读取文件到字节数组:

//读取文件
    public static byte[] getArr() throws Exception{
        File file = new File("C:\\Users\\SongShilun\\Desktop\\mcu6_Files\\Ztest40.MCU6");
        FileInputStream fis = new FileInputStream(file);
        long length = file.length();

        byte[] buffer = new byte[(int) length];

        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        fis.close();
        return buffer;
    }

16进制与字节数组的转化

//字节数组转16进制
    public static String byteArrToHex(byte[] btArr) {
        char strArr[] = new char[btArr.length * 2];
        int i = 0;
        for (byte bt : btArr) {
            strArr[i++] = HexCharArr[bt>>>4 & 0xf];
            strArr[i++] = HexCharArr[bt & 0xf];
        }
        return new String(strArr);
    }


    //16进制转字节
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
	//单个字符转字节
    private static byte charToByte(char c){
        String chars = "0123456789ABCDEF";
        byte b = (byte)chars.indexOf(c);
        return b;
    }

每16个字节换行打印

	//每32个字节换行打印
    public static void formatPrint(String hexStr){
        int no = 0;
        int length = hexStr.length();
        for (int i=0;i<length;i++){
            if ((i+1)%32==0){
                String s = twoSpaceTwo(hexStr.substring(i - 31, i + 1));
                System.out.println("no"+no+":"+s);
                no++;
                if (length-i<32){
                    return;
                }
            }
        }

    }

字符串每隔两位插入空格

	//隔两位打印一个空格----正则表达式方法
    public static String twoSpaceTwo(String replace){
        String regex = "(.{2})";
        replace = replace.replaceAll(regex, "$1 ");
        return replace;
    }


最后一个参考自:https://blog.csdn.net/qq_40321119/article/details/105217092
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值