java:string2hexString 中文字符转码问题解决

来源:互联网 发布:怎么样开淘宝店的流程 编辑:程序博客网 时间:2024/06/08 12:27

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:e4bda0e5a5bde5958ae5958ae5958ae5958a3b617878782d2d2d3d3d3d3e3c3breOrigin:你好啊啊啊啊;axxx---===><;
原创粉丝点击