Java 实现字符串与 Unicode、十六进制编码的相互转换

在开发中有时候需要将字符串转为 Unicode 编码、十六进制编码等,对二进制文件进行编辑时也可以借助十六进制编码实现,因此用 Java 写了一个工具类方便调用。

运行环境

操作系统:Windows 10

Java环境:JDK-17

IDE:Eclipse,工作空间的文件编码格式设置为 UTF-8

具体实现

package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 此类用于字符串与 Unicode、十六进制编码的相互转换
 */
public class UString {

	public static void main(String[] args) {
		String str = "中国 china";
		System.out.println(stringToUnicode(str));

		String unicode = "\\u4e2d \\u56fd \\u20 \\u63 \\u68 \\u69 \\u6e \\u61";
		System.out.println(unicodeToString(unicode));

		String csName = "UTF-8";
		System.out.println(stringToHex(str, csName));

		String hex = "e4 b8 ad e5 9b bd 20 63 68 69 6e 61";
		System.out.println(hexToString(hex, csName));

		csName = "GBK";
		System.out.println(stringToHex(str, csName));

		hex = "d6 d0 b9 fa 20 63 68 69 6e 61";
		System.out.println(hexToString(hex, csName));

		readBinToHex(new File("D:\\Test\\bin.txt"), new File("D:\\Test\\hex.txt"));
		writeHexToBin(new File("D:\\Test\\hex.txt"), new File("D:\\Test\\tmp.txt"));
	}

	/**
	 * 将字符串转换为 Unicode,返回 Unicode
	 * 
	 * @param str 要转换为 Unicode 的字符串
	 */
	public static String stringToUnicode(String str) {
		StringBuffer sb = new StringBuffer();
		for (char c : str.toCharArray()) {
			sb.append(" \\u" + Integer.toHexString(c));
		}
		return sb.toString();
	}

	/**
	 * 将 Unicode 转换为字符串,返回字符串
	 * 
	 * @param unicode 要转换为字符串的 Unicode
	 */
	public static String unicodeToString(String unicode) {
		StringBuffer sb = new StringBuffer();
		for (String s : unicode.split(" ")) {
			sb.append((char) Integer.parseInt(s.replaceAll("\\\\u", ""), 16));
		}
		return sb.toString();
	}

	/**
	 * 将字符串按指定字符集转换为十六进制编码,返回十六进制编码
	 * 
	 * @param str    要转换为十六进制编码的字符串
	 * @param csName 指定的字符集
	 */
	public static String stringToHex(String str, String csName) {
		StringBuffer sb = new StringBuffer();
		byte[] arr;
		try {
			arr = str.getBytes(csName);
		} catch (UnsupportedEncodingException e) {
			System.err.println("指定的字符集“" + csName + "”不受支持,已使用平台的默认字符集。");
			arr = str.getBytes();
		}
		for (byte b : arr) {
			sb.append(Integer.toHexString(b).replaceAll("ffffff", "") + " ");
		}
		return sb.toString();
	}

	/**
	 * 将十六进制编码按指定字符集转换为字符串,返回字符串
	 * 
	 * @param hex    要转换为字符串的十六进制编码
	 * @param csName 指定的字符集
	 */
	public static String hexToString(String hex, String csName) {
		String[] arr = hex.split(" ");
		byte[] b = new byte[arr.length];
		for (int i = 0; i < arr.length; i++) {
			b[i] = (byte) Short.parseShort(arr[i], 16);
		}
		try {
			return new String(b, csName);
		} catch (UnsupportedEncodingException e) {
			System.err.println("指定的字符集“" + csName + "”不受支持,已使用平台的默认字符集。");
			return new String(b);
		}
	}

	/**
	 * 读取二进制文件的字节转换为十六进制编码写入文本文件
	 * 
	 * @param bin 要读取字节的二进制文件
	 * @param txt 要写入十六进制编码的文本文件
	 */
	public static void readBinToHex(File bin, File txt) {
		try (FileInputStream fis = new FileInputStream(bin);
				BufferedWriter bw = new BufferedWriter(new FileWriter(txt))) {
			byte[] arr = new byte[16];
			int len = 0;
			while ((len = fis.read(arr)) != -1) {
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < len; i++) {
					sb.append(Integer.toHexString(arr[i]).replaceAll("ffffff", "") + " ");
				}
				bw.append(sb);
				bw.newLine();
			}
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取文本文件的十六进制编码转换为字节写入二进制文件
	 * 
	 * @param txt 要读取十六进制编码的文本文件
	 * @param bin 要写入字节的二进制文件
	 */
	public static void writeHexToBin(File txt, File bin) {
		try (BufferedReader br = new BufferedReader(new FileReader(txt));
				FileOutputStream fos = new FileOutputStream(bin)) {
			String line = null;
			while ((line = br.readLine()) != null) {
				line = line.substring(0, line.length() - 1);
				String[] arr = line.split(" ");
				byte[] b = new byte[arr.length];
				for (int i = 0; i < arr.length; i++) {
					b[i] = (byte) Short.parseShort(arr[i], 16);
				}
				fos.write(b);
			}
			fos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值