java 文件流 转成16进制字符串,然后再转为文件

记录一个需求情况,文件转为文件流byte[]数组。然后把数组转为16进制的字符串。在把16进制字符串 重组成文件。

示例代码如下:

public static void main(String[] args) throws Exception {
        InputStream fis = new FileInputStream("D:\\text.xlsx");
        //文件先转为byte流数组
        byte[] bytes = FileCopyUtils.copyToByteArray(fis);
        //定义16进制转换后的byte数组
        byte[] afByte;
       //定义16进制字符串
        String hex = "";
        for (int i = 0; i < bytes.length; i++) {
            int ce = bytes[i] & 0xFF;
            //这里不满足两个长度的需要填充0,为了满足一个字节占的是字符串的两位 比如 10的16进制就是a 转为16进制字符串就是0a
            hex = hex+StringUtils.leftPad(Integer.toHexString(ce), 2, "0");
        }
        afByte = getByteArray(hex);
        File file = new File("D:\\test2.xlsx");
        FileCopyUtils.copy(afByte,file);
}

/**
     * 16进制字符串转byte数组
     * @param hexString
     * @return
     */
    public static byte[] getByteArray(String hexString) {
        byte[] result = new byte[hexString.length() >> 1];
        for (int i = 0; i < result.length; i++) {
            char a = hexString.charAt(2 * i);
            char b = hexString.charAt(2 * i + 1);
            String ab = new String(new char[]{a, b});
            result[i] = (byte) Integer.valueOf(ab, 16).intValue();
        }

        return result;
    }

你可能感兴趣的:(java,java,开发语言)