1. 程式人生 > >java:string2hexString 中文字元轉碼問題解決

java:string2hexString 中文字元轉碼問題解決

java 中提供了一些字串轉碼的工具類,比如:Base64,UrlEncoder & UrlDecoder。但是這些類,真的非常有侷限性,轉碼之後的字串,往往不能被當成檔案路徑識別。
於是將 字串轉成16進位制的字串就顯得非常有必要了。因為16進位制的字串就是數字以及英文字母a-f組成的。所以,當成路徑去解析是完全可以的。

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * Created by cat on 2017/8/25.
 */
public class TransStringTool
{
public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException { String origin = "你好啊啊啊啊;axxx---===><;"; byte[] bytes = origin.getBytes(); String hex = bytesToHexString(bytes); System.out.println(Arrays.toString(bytes) + " , "
+ hex); byte[] bb = hexStringToBytes(hex); String rr = new String(bb); System.err.println(Arrays.toString(bb) + " , " + rr); System.err.println("##########################################################"); System.err.println("##########################################################"
); Thread.sleep(10); String result = "origin:" + origin + "\n" + "hexStr:" + str2HexStr(origin) + "\n" + "reOrigin:" + hexStr2Str(str2HexStr(origin)); System.out.println(result); } public static String str2HexStr(String origin) { byte[] bytes = origin.getBytes(); String hex = bytesToHexString(bytes); return hex; } public static String hexStr2Str(String hex) { byte[] bb = hexStringToBytes(hex); String rr = new String(bb); return rr; } private static String bytesToHexString(byte[] src) { StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); } private 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; } /** * Convert char to byte * * @param c char * @return byte */ private static byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); }
  • 這個程式碼不是完全原創的,也借鑑了網上的部分程式碼。不過使用起來的效果是極好的。

輸出如下:

origin:你好啊啊啊啊;axxx---===><;
hexStr:e4bda0e5a5bde5958ae5958ae5958ae5958a3b617878782d2d2d3d3d3d3e3c3b
reOrigin:你好啊啊啊啊;axxx---===><;