Java 字节数组(byte[])与字符串(16进制/Base64)的相互转换

电玩女神 2021-09-22 22:20 547阅读 0赞

本文链接: https://blog.csdn.net/xietansheng/article/details/88421655

MD5、SHA-1 等 Hash 值的计算结果通常转换为 16 进制字符串的形式保存。

RSA 等算法的密钥通常转换为 Base64 字符串保存。图片也可以编码为 Base64 字符串直接以文本的形式放到 HTML 中显示图片。

1. byte[] <-> 16进制字符串

1.1 封装工具类:HexUtils

HexUtils.java工具类完整源码:

  1. package com.xiets.data;
  2. /** * 16进制字符串 与 byte数组 相互转换工具类 */
  3. public class HexUtils {
  4. private static final char[] HEXES = {
  5. '0', '1', '2', '3',
  6. '4', '5', '6', '7',
  7. '8', '9', 'a', 'b',
  8. 'c', 'd', 'e', 'f'
  9. };
  10. /** * byte数组 转换成 16进制小写字符串 */
  11. public static String bytes2Hex(byte[] bytes) {
  12. if (bytes == null || bytes.length == 0) {
  13. return null;
  14. }
  15. StringBuilder hex = new StringBuilder();
  16. for (byte b : bytes) {
  17. hex.append(HEXES[(b >> 4) & 0x0F]);
  18. hex.append(HEXES[b & 0x0F]);
  19. }
  20. return hex.toString();
  21. }
  22. /** * 16进制字符串 转换为对应的 byte数组 */
  23. public static byte[] hex2Bytes(String hex) {
  24. if (hex == null || hex.length() == 0) {
  25. return null;
  26. }
  27. char[] hexChars = hex.toCharArray();
  28. byte[] bytes = new byte[hexChars.length / 2]; // 如果 hex 中的字符不是偶数个, 则忽略最后一个
  29. for (int i = 0; i < bytes.length; i++) {
  30. bytes[i] = (byte) Integer.parseInt("" + hexChars[i * 2] + hexChars[i * 2 + 1], 16);
  31. }
  32. return bytes;
  33. }
  34. }

HexUtils类中的两个公开静态方法:

  1. // byte数组 转换成 16进制小写字符串
  2. static String bytes2Hex(byte[] bytes)
  3. // 16进制字符串 转换为对应的 byte数组
  4. static byte[] hex2Bytes(String hex)

1.2 HexUtils 工具类的使用

  1. package com.xiets.data;
  2. /** * @author xietansheng */
  3. public class Main {
  4. public static void main(String[] args) {
  5. String data = "Hello World";
  6. // byte[] 转换为 16进制字符串
  7. String hex = HexUtils.bytes2Hex(data.getBytes());
  8. System.out.println(hex); // 输出: 48656c6c6f20576f726c64
  9. // 16进制字符串 转换为 byte[]
  10. byte[] bytes = HexUtils.hex2Bytes(hex);
  11. System.out.println(new String(bytes)); // 输出: Hello World
  12. }
  13. }

2. byte[] <-> Base64 字符串

2.1 封装工具类:Base64Utils

Base64Utils.java工具类完整源码:

  1. package com.xiets.data;
  2. import sun.misc.BASE64Decoder;
  3. import sun.misc.BASE64Encoder;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.Closeable;
  6. import java.io.File;
  7. import java.io.FileInputStream;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.OutputStream;
  12. /** * Base64 转换工具 */
  13. public class Base64Utils {
  14. /** * byte数组 转换为 Base64字符串 */
  15. public static String encode(byte[] data) {
  16. return new BASE64Encoder().encode(data);
  17. }
  18. /** * Base64字符串 转换为 byte数组 */
  19. public static byte[] decode(String base64) {
  20. try {
  21. return new BASE64Decoder().decodeBuffer(base64);
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. return new byte[0];
  26. }
  27. /** * 把文件内容编码为 Base64字符串, 只能编码小文件(例如文本、图片等) */
  28. public static String encodeFile(File file) throws Exception {
  29. InputStream in = null;
  30. ByteArrayOutputStream bytesOut = null;
  31. try {
  32. in = new FileInputStream(file);
  33. bytesOut = new ByteArrayOutputStream((int) file.length());
  34. byte[] buf = new byte[1024];
  35. int len = -1;
  36. while ((len = in.read(buf)) != -1) {
  37. bytesOut.write(buf, 0, len);
  38. }
  39. bytesOut.flush();
  40. return encode(bytesOut.toByteArray());
  41. } finally {
  42. close(in);
  43. close(bytesOut);
  44. }
  45. }
  46. /** * 把 Base64字符串 转换为 byte数组, 保存到指定文件 */
  47. public static void decodeFile(String base64, File file) throws Exception {
  48. OutputStream fileOut = null;
  49. try {
  50. fileOut = new FileOutputStream(file);
  51. fileOut.write(decode(base64));
  52. fileOut.flush();
  53. } finally {
  54. close(fileOut);
  55. }
  56. }
  57. private static void close(Closeable c) {
  58. if (c != null) {
  59. try {
  60. c.close();
  61. } catch (IOException e) {
  62. // nothing
  63. }
  64. }
  65. }
  66. }

Base64Utils工具类中的几个公开静态方法:

  1. // byte数组 转换为 Base64字符串
  2. static String encode(byte[] data)
  3. // Base64字符串 转换为 byte数组
  4. static byte[] decode(String base64)
  5. // 把文件内容编码为 Base64字符串, 只能编码小文件(例如文本、图片等)
  6. static String encodeFile(File file)
  7. // 把 Base64字符串 转换为 byte数组, 保存到指定文件
  8. static void decodeFile(String base64, File file)

2.2 Base64Utils 工具类的使用

  1. package com.xiets.data;
  2. import java.io.File;
  3. /** * @author xietansheng */
  4. public class Main {
  5. public static void main(String[] args) throws Exception {
  6. String data = "Hello World";
  7. // 编码: byte[] 转换为 Base64字符串
  8. String base64 = Base64Utils.encode(data.getBytes());
  9. System.out.println(base64); // 输出: SGVsbG8gV29ybGQ
  10. // 解码: Base64字符串 转换为 byte[]
  11. byte[] bytes = Base64Utils.decode(base64);
  12. System.out.println(new String(bytes)); // 输出: Hello World
  13. /* * 对文件进行 Base64 编码 */
  14. // 编码: 把文件内容编码为 Base64字符串
  15. String fileBase64Str = Base64Utils.encodeFile(new File("demo.png"));
  16. System.out.println(fileBase64Str);
  17. // Base64 字符串格式的图片在 html img 标签中的直接显示格式:
  18. // <img src="data:image/png;base64,fileBase64Str"/>
  19. // 解码: 把 Base64字符串 转换为 byte数组, 保存到指定文件
  20. Base64Utils.decodeFile(fileBase64Str, new File("demo2.png"));
  21. // 对比 demo.png 和 demo2.png 两个文件的 MD5 将会完全相同
  22. }
  23. }

发表评论

表情:
评论列表 (有 0 条评论,547人围观)

还没有评论,来说两句吧...

相关阅读